if(typeof develop_mode==='undefined')
{
    develop_mode = false;
}
if(typeof audio_danger==='undefined')
{
    audio_danger = false;
}
if(typeof select_language==='undefined')
{
    select_language = false;
}
if (typeof map_tiles_leaflet==='undefined') {
    map_tiles_leaflet = {
        url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
        options: {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }
    }
}
'use strict';
var command_list_cookie = new Object();
try
{
    command_list_cookie=JSON.parse(get_cookie('command_list'));
}
catch (err)
{
    
}
if (get_cookie('token')==undefined||get_cookie('token')=='')
{
    window.location='./auth.html';
}
var app = angular
.module('vegaLora',['ngAutocomplete','ngAnimate', 'ngSanitize', 'mgcrea.ngStrap','nya.bootstrap.select','isteven-multi-select','naturalSort','rzModule','leaflet-directive',"kendo.directives",'ngMaterial', 'ngMessages'])
.config(function($logProvider){
  $logProvider.debugEnabled(false);
})
.config(function($mdDateLocaleProvider) {
    $mdDateLocaleProvider.shortDays = ['ВС','ПН', 'ВТ', 'СР', 'ЧТ', 'ПТ', 'СБ'];
    $mdDateLocaleProvider.month = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',  'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];
    $mdDateLocaleProvider.shortMonths = ['Янв', 'Февр', 'Март', 'Апр', 'Май', 'Июнь',  'Июль', 'Авг', 'Сент', 'Окт', 'Нояб', 'Дек'];
    $mdDateLocaleProvider.formatDate = function(date) {
       return moment(date).format('DD MMMM YYYY');
    };
    $mdDateLocaleProvider.parseDate = function(dateString) {
        var m = moment(dateString,'DD MMMM YYYY',true)
        return m.isValid()?m.toDate():new Date(NaN);
     };
})
.constant('ws',{address: (get_cookie('ws_address')!=undefined&&get_cookie('ws_address')!='undefined')?get_cookie('ws_address').replace(/"/g,''):address_ws})
.factory('storage',function (){
    var storage = new Object();
    storage.devices = new Devices();
    storage.edit_device_main = new Object();
    storage.map_nav = new map_nav('audio',audio_danger);//Набор списков дерева выбора устройств
    storage.date_range = new date_range();//период времени
    storage.type_cargo_list  = cargoTypes;
    storage.type_device_list  = new type_device(deviceTypes);
    storage.type_channel_list = new type_channels(channelTypes);// заполнения списка типов канала
    storage.status_channel_list = new status_channel_list(JSON.parse(JSONstatus_list));//заполнения списка статусов
    storage.color_list = new color_list(JSON.parse(JSONcolor_list));//заполнения списка цветов
    storage.events = new Events();
    storage.getSelectedTypeDevice = function ()
    {
        if (this.edit_device_main)
        {
            var dt = undefined;
            if (this.edit_device_main.selected_device_type)  
            {
                dt = this.edit_device_main.selected_device_type;
            }
            else
            {
                dt = this.edit_device_main.device_type;
            }
            dt = this.type_device_list.get_type_device(dt);
            if (dt)
            {
                // console.log(dt.url_image);
                return dt;
            }
        }
        // console.log('Пустой');
        return {
            url_image: './images/devices/none.png'
        };
    }
    storage.getNameTypeCargo = function(id)
    {
        for (var i = 0 ; i<storage.type_cargo_list.length; i++)
        {
            var type = storage.type_cargo_list[i];
            if (type.id == id)
            {
                return type.name;
            }
        }
        return '-';
    }
    storage.getRecommendationDeviceType = function ()
    {
        var appEui = this.edit_device_main.appEui;
        return this.type_device_list.get_type_device_on_appEui(appEui);
    }
    storage.selectTypeDevice = function(type)
    {
        this.edit_device_main.selected_device_type=type.id.toString();
    }
    //Добавление устройства в дерево
    storage.add_device_list = function (newDevice)
    {
        var temp = this.devices.get_device(newDevice.devEui);
        if (!temp)
        {
            this.devices.devices_list.push(newDevice);
        }
        else
        {
            this.devices.reconnect_device(newDevice);  
        }
        for (var i=0;i<newDevice.channels.length;i++)
        {
            this.map_nav.set_level_1(newDevice.channels[i].name_level_1,newDevice.channels[i].address_level_1);
            this.map_nav.set_level_2(newDevice.channels[i].level_2);
            this.map_nav.set_level_3(newDevice.channels[i].name);
            this.map_nav.add(newDevice.channels[i]);
        }      
    };
    return storage;
})
.factory('WS', ['$timeout','ws','storage','$interval',function($timeout,ws,storage,$interval) {
    if (get_cookie('token')==undefined||get_cookie('token')=='')
        {
            window.location='./auth.html';
        }
    var last_del;
    var send_vega = new Object();//объект вывода интерфейса для общения с WS
    send_vega.danger_num = new Array();
    send_vega.logs = new Logs();
    send_vega.last_time_server = 0;
    send_vega.status=true;
    send_vega.reload_status=false;
    send_vega.auth_status=false;
    send_vega.loader=false;//запускаем лоадер
    send_vega.loader_auth=false;
    send_vega.count_get_data=0;
    $interval(function (){ 
        send_vega.ping();
        var currentTime = new Date().getTime();
        var passedTime = send_vega.last_time?(currentTime-send_vega.last_time):0;
        if (passedTime>300000)
        {
            send_vega.auth_status=false;
            send_vega.status=false;
            if (!send_vega.reload_status)
            {
                $timeout(function (){ 
                    send_vega.reload_status=true; 
                    send_vega.reload();  
                },10000);
            }
            console.log('WebSocket закрыт ping ');
        }
    },15000);
    send_vega.danger_num.get=function(devEui,num)
    {
        var res=0;
        for (var i = 0 ; i< this.length;i++)
        {
            if (devEui=this.devEui&&num==this.devEui)
            {
                res++
            }
            return res;
        }
    }
    send_vega.ping=function ()
    {     //ОТПРАВКА запроса ping
        var tempObj = new Object();
        tempObj.cmd='ping_req';
        my_ws.send(JSON.stringify(tempObj)); //отправка запроса на получения списка устройств с атрибутами
    };
    send_vega.send_json = function(json)
    {
        try
        {
            my_ws.send(json); 
            send_vega.loader=true;//запускаем лоадер
        }
        catch (err)
        {
            console.log('Ошибка отправки json на ws');
        }
    }
    send_vega.token_auth_req = function ()
    {
        my_ws.send(JSON.stringify({
            cmd:'token_auth_req',
            token:get_cookie('token')
        }));
    }
    //отправка запроса get_device_appdata_req
    send_vega.send_get_device=function ()
    {   
        var tempObj = new Object();
        tempObj.cmd='get_device_appdata_req';
        tempObj.keyword=['add_data_info'];
        my_ws.send(JSON.stringify(tempObj)); //отправка запроса на получения списка устройств с атрибутами
        send_vega.loader=true;//запускаем лоадер
    }
    
    //Запрос данных с устройства
    send_vega.send_get_device_data_req = function(devEui,date_from,date_to,limit,port)
    {
        if (devEui!=undefined)
        {
           var tempObj = new Object();
           tempObj.cmd = "get_data_req";
           tempObj.devEui = devEui;
           if (date_from!=undefined||date_to!=undefined||limit!=undefined) //в случае если имеются дополднительные параметры для запроса
           {
               tempObj.select = new Object();
               if (date_from!=undefined)
               {
                   tempObj.select.date_from=date_from;
               }
               if (date_to!=undefined)
               {
                   tempObj.select.date_to=date_to;
               }
               if (limit!=undefined)
               {
                   tempObj.select.limit=limit;
               }
               if (port!=undefined)
               {
                   tempObj.select.port=port;
               }
           }
           my_ws.send(JSON.stringify(tempObj));
           send_vega.loader=true;
           send_vega.count_get_data++;
        }
        else
        {
            console.log('NO !! send_get_device_data_req');
        }
    }
    send_vega.send_data_multy_kostil = function(data,devEui,ack,port)
    {
        if (ack===undefined) ack=false;
        if (port===undefined) port=2;
        if ( typeof data === 'string' ) data = [data];
        if ( typeof data !== 'object' ) data = [];
        
        for( var i = 0; i < data.length; i++ )
        {
            
            if ( typeof data[i] === 'string' )
            {
                (function(i){
                    $timeout(function() {
                        send_vega.send_data(data[i],devEui,ack,port,false);
                        // console.log(data[i]);
                    }, i *2000);
                })(i);
            }
        }
        send_vega.waitingResponse = true;
    }
    send_vega.send_data_multy = function(data,devEui,ack,port)
    {
        if (ack===undefined) ack=false;
        if (port===undefined) port=2;
        if ( typeof data === 'string' ) data = [data];
        if ( typeof data !== 'object' ) data = [];
        var tempObj = {
            cmd:'send_data_req',
            data_list:[]
        };
        for(var i = 0; i < data.length; i++)
        {
            var d = data[i];
            if( typeof d === 'string' )
            {
                var item = {
                    devEui:devEui,
                    data:d,
                    port:port,
                    ack:ack
                }
                tempObj.data_list.push(item);
            }
            send_vega.last_data_request = d;
        }
        send_vega.waitingResponse = true;
        my_ws.send(JSON.stringify(tempObj));
    }
    send_vega.send_data = function(data,devEui,ack,port,task)
    {
        if (task === undefined) task = true;
        if (ack===undefined) ack=false;
        if (port===undefined) port=2;
        var tempObj={
            cmd:'send_data_req',
            data_list:[
                {
                    devEui:devEui,
                    data:data,
                    port:port,
                    ack:ack
                }
            ]
        };
        send_vega.last_data_request = data;
        if(task) send_vega.waitingResponse = true;
        my_ws.send(JSON.stringify(tempObj));
    }
    //запрос manage_device_appdata_req
    send_vega.checkValidRXType = function (type)
    {
      try
      {
        let validType = typeof type === 'string';
        if( validType )
        {
            let types = type.split('+');
            if( types.indexOf( 'UNCONF_UP' ) > -1 || types.indexOf( 'CONF_UP' ) > -1 )
            {
              return true;
            }
        }
        return false;
      }
      catch (e)
      {
        return false;
      }
    }
    send_vega.saveDevice_universal=function(devEui,object,device_type,version)
    {
       var tempDevice = new Object();
       tempDevice.devEui =devEui;

       if( version === undefined )
       {
            var selectedDevice = storage.devices.get_device(storage.edit_device_main.devEui);
            version = storage.type_device_list.get_key_default_settings_type_device( device_type, selectedDevice.appEui ).toString();
       }
       if( version === undefined ) version = 0;

       tempDevice['other_info_'+object.num_channel] = new Channel(object);
       tempDevice['device_type'] = device_type.toString();
       tempDevice['version'] =  version.toString();
       delete tempDevice['other_info_'+object.num_channel].history;
       delete tempDevice['other_info_'+object.num_channel].statistics;
       delete tempDevice['other_info_'+object.num_channel].danger;
       tempDevice['other_info_'+object.num_channel]=JSON.stringify(tempDevice['other_info_'+object.num_channel]);
       var tempObj = new Object();
       tempObj.cmd="manage_device_appdata_req";
       tempObj.data_list = new Array();
       tempObj.data_list[0]=tempDevice;
       my_ws.send(JSON.stringify(tempObj));
    }
    send_vega.save_device_main=function(devEui,device_type,version)
    {
       var tempDevice = new Object();
       tempDevice.devEui =devEui;
       //формируем сводный атрибут с парамитрами устройства(канала)
       tempDevice['device_type']=device_type;
       tempDevice['version']=version;
       var tempObj = new Object();
       tempObj.cmd="manage_device_appdata_req";
       tempObj.data_list = new Array();
       tempObj.data_list[0]=tempDevice;
       my_ws.send(JSON.stringify(tempObj));
    }
    //Запрос delete_device_appdata_req -удаления атрибутов для канала(устройства)
    send_vega.clear_device=function(devEui)
    {
       var tempDevice = new Object();
       tempDevice.cmd='delete_device_appdata_req';
       tempDevice.data_list = new Array();
       this.last_del = [devEui,false];
       var tempObj = new Object();
       tempObj.devEui = devEui;
       tempDevice.data_list.push(tempObj);
       my_ws.send(JSON.stringify(tempDevice));
    }
    send_vega.deleteDevice=function(devEui,num_channel)
    {
       var tempDevice = new Object();
       tempDevice.cmd='delete_device_appdata_req';
       tempDevice.data_list = new Array();
       this.last_del = [devEui,num_channel];
       var tempObj = new Object();
       tempObj.devEui = devEui;
       tempObj.delete_keys=['other_info_'+num_channel];
       tempDevice.data_list.push(tempObj);
       my_ws.send(JSON.stringify(tempDevice));
    }
    send_vega.refrash_last_time_server = function(ts)
    {
        var validTs = ts!==undefined;
        if (validTs)
        {
            ts = parseInt(ts);
            if (!isNaN(ts)&&ts>send_vega.last_time_server)
            {
                send_vega.last_time_server = ts;
            }
        }
    }
    //парсер сообщения от WS
    var parse_vega_api = function(json)
    {
        try
        {
            var scope = angular.element($("body")).scope();
            var json = JSON.parse(json);
            //обработка сообщения get_device_appdata_resp - получен список устройств
            if (json.cmd=='get_device_appdata_resp'&&json.status&&json.devices_list&&json.devices_list!=undefined)
            {
                var tempObj = new Object();
                tempObj.address = new Array();
                for (var i=0; i<json.devices_list.length;i++)
                {    
                    var newdevice = new device();
                    var res = newdevice.set_device(json.devices_list[i],storage.type_device_list.get_type_device(json.devices_list[i].device_type));
                    if (res)
                    {
                         storage.add_device_list(newdevice);
                    }
                }
                storage.devices.full_devices_list=json.devices_list;
                storage.devices.get_statistics(storage.date_range);
                storage.devices.groupingDevice();
                scope.$apply(function (){ 
                    scope.storage; 
                    send_vega.loader=false; 
                    scope.loadPage = false;
                    if(scope.check_page!=11)
                    {
                        scope.editDevice.init();
                    }
                })
                return true;
            }
            else if (json.cmd=='ping_resp')
            {
                return true;
            }
            else if (json.cmd == 'send_data_resp')
            {
                if (json.status)
                {
                    for (var i = 0; i<json.append_status.length; i++)
                    {
                       if (!json.append_status[i].status)
                       {
                        scope.universalAlert('Не удалось отправить данные на устройство, обратитесь к администратору, код ошибки 1134');
                       }
                       else
                       {
                          if (send_vega.waitingResponse ) 
                          {
                            scope.universalAlert('Данные поставлены в очередь отправки на устройство');
                            //   if( send_vega.last_data_request !== '00' ) $('#settingsDevice').modal('hide');
                          }
                       }
                    }
                }
                else
                {
                    scope.universalAlert('Не удалось отправить данные на устройство, обратитесь к администратору, код ошибки 1133', 'Ошибка!');
                }
                send_vega.waitingResponse = false;
            }
            else if (json.cmd == 'alter_user_resp')
            {
                var _deleted = json.deleted;
                var _command_list = json.command_list;
                var _device_access = json.device_access;
                var _devEui_list = json.devEui_list;
                var _consoleEnable = json.consoleEnable;
                var _rx_settings = json.rx_settings;
                if (_command_list)
                {
                    var my_command_list = new command_list();
                    my_command_list.set_command_list_array(_command_list);
                    set_cookie('command_list',JSON.stringify(_command_list));
                    scope.command_list_cookie= my_command_list;
                }
                if (_deleted||_device_access!=undefined||_devEui_list)
                {
                    window.location.reload();
                }
            }
            else if (json.cmd=='token_auth_resp')
            {
                if (json.status)
                {
                    set_cookie('token',json.token);
                    send_vega.auth_status=true;
                    send_vega.send_get_device();
                    send_vega.loader_auth=false;
                }
                else
                {
                    delete_cookie('token');
                    delete_cookie('login');
                    delete_cookie('command_list');
                    window.location='./auth.html';
                }
            }
            else if (json.cmd=='close_auth_resp')
            {
                if (json.status)
                {
                    delete_cookie('token');
                    delete_cookie('login');
                    delete_cookie('command_list');
                    window.location='./auth.html';
                }
                else
                {
                    scope.universalAlert("Не удалось выйти ");
                }
            }
            else if (json.cmd == 'manage_device_appdata_resp'&&json.update_status!=undefined)
            { 
                var tmp = new Object();
                tmp.address_level_1 = scope.editDevice.level_1.address_level_1;
                tmp.name_level_1 = scope.editDevice.level_1.name_level_1;
                tmp.level_2 = scope.editDevice.level_2;
                tmp.name = scope.editDevice.name;
                tmp.num_channel = scope.editDevice.num_channel;
                tmp.status = scope.editDevice.status;
                tmp.color = scope.editDevice.color.id;
                tmp.info_channel = scope.editDevice.info_channel;
                tmp.init_value = scope.editDevice.init_value;
                tmp.last_date = new Date(scope.editDevice.last_date).getTime();
                tmp.date_installation = new Date(scope.editDevice.date_installation).getTime();
                tmp.date_shipment = new Date(scope.editDevice.date_shipment).getTime();
                
                tmp.type_channel = scope.editDevice.type_channel.id;
                tmp.history = scope.editDevice.history;
                tmp.division = scope.editDevice.division;
                tmp.calib_interval = scope.editDevice.calib_interval;
                tmp.ia = scope.editDevice.ia;
                tmp.mac = scope.editDevice.mac;
                tmp.key = scope.editDevice.key;
                tmp.model = scope.editDevice.model;
                tmp.serial = scope.editDevice.serial;
                tmp.personal_num = scope.editDevice.personal_num;
                tmp.type_meter = scope.editDevice.type_meter;
                tmp.kt = scope.editDevice.kt;
                tmp.security_name = scope.editDevice.security_name;
                tmp.hall_1_name = scope.editDevice.hall_1_name;
                tmp.hall_2_name = scope.editDevice.hall_2_name;
                tmp.min_t = scope.editDevice.min_t;
                tmp.max_t = scope.editDevice.max_t;
                tmp.water = scope.editDevice.water;
                tmp.instrument = scope.editDevice.instrument;
                tmp.instrument2 = scope.editDevice.instrument2;
                tmp.unit = scope.editDevice.unit;
                tmp.min_v = scope.editDevice.min_v;
                tmp.max_v = scope.editDevice.max_v;
                tmp.min_normal_v = scope.editDevice.min_normal_v;
                tmp.max_normal_v = scope.editDevice.max_normal_v;
                tmp.security_name_2 = scope.editDevice.security_name_2;
                tmp.sensor_name_1 = scope.editDevice.sensor_name_1;
                tmp.sensor_name_2 = scope.editDevice.sensor_name_2;

                for(var i = 1; i<=10; i++)
                {
                    tmp[`temperature_sensor_name_${i}`] = scope.editDevice[`temperature_sensor_name_${i}`];
                }
                
                tmp.name_sensor_in_1=scope.editDevice.name_sensor_in_1;
                tmp.name_sensor_in_2=scope.editDevice.name_sensor_in_2;
                tmp.name_sensor_out_1=scope.editDevice.name_sensor_out_1;
                tmp.name_sensor_out_2=scope.editDevice.name_sensor_out_2;
                
                
                tmp.telephones = scope.editDevice.telephones;
                tmp.emails = scope.editDevice.emails;
                tmp.telegram_chats = scope.editDevice.telegram_chats;
                tmp.message_sms = scope.editDevice.message_sms;
                tmp.message_messenger = scope.editDevice.message_messenger;
                tmp.sms = scope.editDevice.sms;
                tmp.email = scope.editDevice.email;
                tmp.telegram = scope.editDevice.telegram;
                tmp.enable_danger = scope.editDevice.enable_danger;
                tmp.user_message_danger = scope.editDevice.user_message_danger;
                tmp.app_message_danger = scope.editDevice.app_message_danger;
                tmp.voice = scope.editDevice.voice;
                tmp.voice_message = scope.editDevice.voice_message;
                tmp.count_rate = scope.editDevice.count_rate;
                tmp.count_phase = scope.editDevice.count_phase;
                tmp.display_power_profile = scope.editDevice.display_power_profile;
                tmp.relay = scope.editDevice.relay;
                
                tmp.provider = scope.editDevice.provider;
                tmp.typeCargo = scope.editDevice.typeCargo;
                tmp.cargo = scope.editDevice.cargo;
                tmp.version = scope.editDevice.version.toString();
                for (var i =0;i<json.update_status.length;i++)
                {
                    if (json.update_status[i].devEui==scope.editDevice.device.devEui&&json.update_status[i].status)
                    {
                        var dev = storage.devices.get_device(scope.editDevice.device.devEui);
                        var newChannel = scope.storage.devices.get_channel(scope.editDevice.device.devEui, scope.editDevice.num_channel);
                        newChannel.edit(tmp,dev);                                                                                                                                                                                                                                                                                                                                                           
                        scope.storage.map_nav.set_level_1(scope.editDevice.level_1.name_level_1,scope.editDevice.level_1.address_level_1);
                        scope.storage.map_nav.set_level_2(scope.editDevice.level_2);
                        scope.storage.map_nav.add(newChannel);
                        scope.$apply(function (){
                            scope.map_nav; scope.storage; send_vega.loader=false; 
                        });
                      $('#infoDeviceEditor').popover('hide');
                      scope.infoDeviceEditor = false;
                      if (scope.editDevice.edit)
                      {
                          swal(scope.editDevice.name, "Изменения были сохранены", "success");
                      }
                      else
                      {
                          swal(scope.editDevice.name, "Устройство было успешно добавлено", "success");
                          scope.select_channel(scope.editDevice.device.devEui,tmp.num_channel);
                      }
                    }
                    else if (json.update_status[i].devEui==storage.edit_device_main.devEui&&storage.edit_device_main.device_type!=undefined)
                    {
                        var newdevice = new device();
                        var res = newdevice.set_device(storage.edit_device_main,storage.type_device_list.get_type_device(storage.edit_device_main.device_type));
                        if (res)
                        {
                            var old_device = storage.devices.get_device(newdevice.devEui);
                            if (old_device!=undefined&&old_device&&old_device!=false)
                            {
                                for (var j = 0; j <storage.devices.devices_list.length;j++ )
                                {
                                    if (storage.devices.devices_list[j].devEui = newdevice.devEui)
                                    {
                                        storage.devices.devices_list[j].device_type = newdevice.device_type;
                                        storage.devices.devices_list[j].version = newdevice.version.toString();
                                    }
                                }
                                for (var j = 0; j <storage.devices.full_devices_list.length;j++ )
                                {
                                    if (storage.devices.full_devices_list[j].devEui = newdevice.devEui)
                                    {
                                        storage.devices.full_devices_list[j].device_type = newdevice.device_type;
                                        storage.devices.full_devices_list[j].version = newdevice.version.toString();
                                    }
                                }
                            }
                            else
                            {
                             storage.add_device_list(newdevice);
                            }
                        }
                        storage.devices.groupingDevice();
                        scope.$apply(function (){
                            scope.map_nav; scope.storage=storage; send_vega.loader=false; 
                        });
                    }
                }
            }
            else if (json.cmd == 'delete_device_appdata_resp'&&json.delete_status!=undefined)
            { 
                for (var i =0;i<json.delete_status.length;i++)
                {
                    if (json.delete_status[i].devEui==scope.WS.last_del[0]&&json.delete_status[i].status)
                    {
                        if (!scope.WS.last_del[1])
                        {
                            
                        }
                        if (scope.WS.last_del[0]&&scope.WS.last_del[1])
                        {
                            $('#infoDeviceEditor').popover('hide');
                            scope.infoDeviceEditor = false;
                            var channelFromDevicesList = scope.storage.devices.get_channel(scope.WS.last_del[0], scope.WS.last_del[1]);
                            var originalDevice = scope.storage.devices.get_device_original(scope.WS.last_del[0]);
                            var nameKeyDelete = 'other_info_'+scope.WS.last_del[1];
                            if ( isObject(originalDevice) && originalDevice[nameKeyDelete] !== undefined )
                            {
                                delete originalDevice[nameKeyDelete];
                            }
                            channelFromDevicesList.edit(new Object());      
                            scope.WS.last_del = new Array();
                            scope.storage.devices.groupingDevice();
                            scope.$apply(function (){ scope.map_nav; scope.storage; send_vega.loader=false; 
                            });
                            if (scope.editDevice.edit)
                            {
                                swal(scope.editDevice.name, "Устройство было успешно удалено из IotVegaPulse", "success");
                            }
                            scope.check_page = 1;
                            
                        }
                        else if (scope.WS.last_del[0]&&!scope.WS.last_del[1])
                        {
                            scope.storage.devices.delete_device(scope.WS.last_del[0]);      
                            scope.WS.last_del = new Array();
                            scope.storage.devices.groupingDevice();
                            scope.$apply(function (){ 
                                scope.map_nav; 
                                scope.storage; 
                                send_vega.loader=false; 
                            });
                            $('#edit_device_main').modal('hide');
                        }
                    }
                }
            }
            //обработка сообщения get_device_data_resp получен набор данных
            else if (json.cmd=='get_data_resp'&&json.status&&json.data_list&&json.data_list!=undefined)
            {
                send_vega.count_get_data--;
                if (json.data_list!=undefined&&json.data_list.length==50000)
                {
                    scope.universalAlert('Мы загрузили только часть данных за вабранный период, поскольку их слишком много. Попробуйте выбрать меньший промежуток времени.');
                }
                var ok = false;
                for (var i =0; i<storage.devices.devices_list.length;i++)
                { 
                    var currentDevice = storage.devices.devices_list[i];
                    var currentDeviceDevEui = currentDevice.devEui;
                    var keys = {};
                    if (currentDeviceDevEui==json.devEui)
                    {
                        for (var key in currentDevice.channels)
                        {
                            var currentChannel = currentDevice.channels[key];
                            if(send_vega.statusRequestSetting||send_vega.statusRequestInfo||send_vega.statusRequestDiagnostic) continue;
                            if(currentDevice.device_type==30)
                            {
                                var validMac = typeof currentChannel.mac === 'string' && currentChannel.mac.length == 12;
                                var validKey = typeof currentChannel.key === 'string';
                                if( validMac && validKey)
                                {
                                    keys[currentChannel.mac.toLowerCase()] = currentChannel.key;
                                }
                            }
                            var tempHistoryLast=0;
                            for (var t=0;t<currentChannel.history.length;t++)
                            {
                                if (tempHistoryLast==0||currentChannel.history[t].time>tempHistoryLast.time)
                                {
                                    tempHistoryLast=currentChannel.history[t];
                                }
                            }
                            currentChannel.temp_history = new Object();
                            currentChannel.history = new Array();
                            if (tempHistoryLast!=0&&tempHistoryLast!=undefined)
                            {
                                currentChannel.history.push(tempHistoryLast);
                                currentChannel.temp_history[tempHistoryLast.time]=true;
                            }
                        }
                        ok=true;

                        // 
                        // if(currentDevice.device_type==30)
                        // {
                        //     var channels = currentDevice.channels;
                        //     for(var i = 0 ; i < channels.length; i++ )
                        //     {
                        //         var channel = channels[i];
                        //         var validMac = typeof channel.mac === 'string' && channel.mac.length == 12;
                        //         var validKey = typeof channel.key === 'string';
                        //         if( validMac && validKey)
                        //         {
                        //             keys[channel.mac.toLowerCase()] = channel.key;
                        //         }
                        //     }
                        // }


                        for (var j=0;j<json.data_list.length;j++)
                        {
                            send_vega.refrash_last_time_server(json.data_list[j].ts);
                            if ( send_vega.checkValidRXType( json.data_list[j].type ) )
                            {
                                storage.devices.add_history(json.data_list[j],i,storage.date_range,keys);
                                var port = json.data_list[j].port;
                                if ( port === 3 )
                                {
                                    currentDevice.setSettings(json.data_list[j]);
                                    currentDevice.refreshTempSetting();
                                }
                                else if ( port === 85 )
                                {
                                    currentDevice.setDiagnostic(json.data_list[j]);
                                }
                                else if ( port === 195 )
                                {
                                    currentDevice.setInfo(json.data_list[j]);
                                }
                            }   
                        }
                        continue;
                    }
                }
                send_vega.statusRequestSetting = false;
                send_vega.statusRequestDiagnostic = false;
                send_vega.statusRequestInfo = false;
                storage.devices.get_statistics(storage.date_range);
                if (scope.managerReport.loader===true)
                {
                    var deletedOfQueue = false;
                    for (var key in scope.managerReport.queueWaiting)
                    {
                        if (scope.managerReport.queueWaiting[key].devEui===json.devEui)
                        {
                           deletedOfQueue = true;
                           scope.managerReport.queueSuccess[key] = scope.managerReport.queueWaiting[key]; 
                           delete scope.managerReport.queueWaiting[key];
                        }
                    }
                    if (scope.managerReport.cCount!==0)
                    {
                        if (deletedOfQueue)
                        {
                            var devEui = scope.managerReport.firstChannel.devEui;
                            var start = scope.managerReport.date_range.getStart()*1000;
                            var end = scope.managerReport.date_range.getEnd()*1000;
                            var validSelectedDevice = isObject(scope.managerReport.firstChannel) && isObject(scope.managerReport.firstChannel._self) ;
                            if (validSelectedDevice&&(scope.managerReport.firstChannel._self.device_type == 12 || scope.managerReport.firstChannel._self.device_type == 27))
                            {
                                start = start - moment().utcOffset()*60*1000-DAY_MS;
                                end = end - moment().utcOffset()*60*1000+DAY_MS;
                            }
                            
                            
                            switch (scope.managerReport.selectedType.id) {
                                case 1:
                                    start = start-DAY_MS;
                                    end = end+DAY_MS
                                    send_vega.send_get_device_data_req(devEui,start,end,50000);
                                    break;
                                case 2:
                                    send_vega.send_get_device_data_req(devEui,undefined,undefined,10);
                                    break;  
                                case 3:
                                    send_vega.send_get_device_data_req(devEui,scope.start,end,50000);
                                    break;
                                case 4:
                                    send_vega.send_get_device_data_req(devEui,start,end,50000);
                                    break;
                                case 5:
                                    send_vega.send_get_device_data_req(devEui,start,end,50000);
                                    break;
                                case 7:
                                    send_vega.send_get_device_data_req(devEui,undefined,undefined,10);
                                    break;
                                default:
                                    break;
                            }
                            return;
                        }
                    }
                    else
                    {
                        scope.managerReport.generation();
                    }
                    //проверяем осталось ли чего, если нет то loader прикрываем и даем команду грузить отчет или запрашиваем данные для след устройства в очереди
                }
                var dataForselectedDevice = storage.devices.select_channel_temp.devEui == json.devEui;
                if (dataForselectedDevice)
                {
                    scope.showDataMap('get_data_resp');
                }
                scope.$apply(function (){ 
                    scope.storage; 
                    send_vega.loader=false; 
                    scope.managerReport; 
                });
                scope.reload_full_charts();
                return ok;
            }
            //получено сообщение delete_device_appdata_resp  - было удалено устройство
            else if (json.cmd=='delete_device_appdata_resp'&&json.status)
            {
                $('#infoDeviceEditor').popover('hide');
                scope.infoDeviceEditor = false;
                scope.universalAlert('Устройство было успешно удалено');
                scope.check_page = 1;
                if (scope.editDevice.edit)
                {
                    swal(scope.editDevice.name, "Устройство было успешно удалено из IotVegaPulse", "success");
                }
            }
            //Получено новое сообщение от устройства
            else if ( json.cmd == 'rx' )
            {
                if ( send_vega.checkValidRXType( json.type ) )
                {
                    var ok = false;
                    for (var i =0; i<storage.devices.devices_list.length;i++)
                    {
                        if (storage.devices.devices_list[i].devEui==json.devEui)
                        {
                            var _device = storage.devices.devices_list[i];
                            var dt = parseInt(_device.device_type);
                            var version = _device.version!==undefined?_device.version.toString():_device.version;
                            var currentVersion = -1;
                            if(version) version = parseInt(version);
                            if(!isNaN(version)) currentVersion = version;
                            send_vega.refrash_last_time_server(json.ts);
                            var keys = {};
                            if(_device.device_type==30)
                            {
                                var channels = _device.channels;
                                for(var c = 0 ; c < channels.length; c++ )
                                {
                                    var channel = channels[c];
                                    var validMac = typeof channel.mac === 'string' && channel.mac.length == 12;
                                    var validKey = typeof channel.key === 'string';
                                    if( validMac && validKey)
                                    {
                                        keys[channel.mac.toLowerCase()] = channel.key;
                                    }
                                }
                            }
                            var res = storage.devices.add_history(json,i,storage.date_range,keys);
                            if (json.port === 3)
                            {
                                storage.devices.devices_list[i].setSettings(json);
                            }
                            else if ( json.port === 85 )
                            {
                                storage.devices.devices_list[i].setDiagnostic(json);
                            }
                            else if ( json.port === 195 )
                            {
                                storage.devices.devices_list[i].setInfo(json);
                            }
                            var channel = new Object();
                            var num_channel;
                            if (!isNaN(dt)&&res)
                            {
                                switch (dt) {
                                    case 1:
                                        if(currentVersion>=2)
                                        {
                                            var reason = res.reason;
                                            if(reason >= 1 && reason <= 4 ) 
                                            {
                                                channel = storage.devices.get_channel(_device.devEui,reason);
                                                var validChannel = channel!==undefined&&channel.name!==undefined;
                                                if(validChannel&&channel.enable_danger)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(_device.devEui,reason,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            num_channel = res.num_channel!==undefined?parseInt(res.num_channel):false;
                                            if (num_channel!==false&&!isNaN(num_channel))
                                            {
                                                channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                                var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                                if (validChannel)
                                                {
                                                    if (channel.name!==undefined)
                                                    {
                                                        if (res.type_package==2)
                                                        {
                                                            if (channel.enable_danger)
                                                            {
                                                                storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,channel.num_channel,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                                storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                                channel.danger = true;
                                                            }
                                                            send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                        }
                                                        else
                                                        {
                                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                        }
                                                    }
                                                    else
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        break;
                                    case 11:
                                        if(currentVersion>=2)
                                        {
                                            var reason = res.reason;
                                            if(reason >= 1 && reason <= 4 ) 
                                            {
                                                channel = storage.devices.get_channel(_device.devEui,reason);
                                                var validChannel = channel!==undefined&&channel.name!==undefined;
                                                if(validChannel&&channel.enable_danger)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(_device.devEui,reason,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else if(reason == 5)
                                            {
                                                if(typeof _device.channels === 'object')
                                                {
                                                    var count = 0;
                                                    for(var key = 0; key <= _device.channels.length; key++)
                                                    {
                                                        channel = _device.channels[key];
                                                        var validChannel = channel!==undefined&&channel.name!==undefined;
                                                        if(validChannel&&channel.enable_danger)
                                                        {
                                                            storage.map_nav.set_history_danger(_device.devEui,channel.num_channel,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                            storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                            channel.danger = true;
                                                            send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                        }
                                                    }
                                                    if(count === 0)
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            num_channel = res.num_channel!==undefined?parseInt(res.num_channel):false;
                                            if (num_channel!==false&&!isNaN(num_channel))
                                            {
                                                channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                                var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                                if (validChannel)
                                                {
                                                    if (channel.name!==undefined)
                                                    {
                                                        if (res.type_package==2&&channel.enable_danger)
                                                        {
                                                            if (channel.enable_danger)
                                                            {
                                                                storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,channel.num_channel,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                                storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                                channel.danger = true;
                                                            }
                                                            send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                        }
                                                        else
                                                        {
                                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                        }
                                                    }
                                                    else
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        break;
                                    case 2:
                                        num_channel = res.num_channel!==undefined?parseInt(res.num_channel):false;
                                        
                                        if (num_channel!==false&&!isNaN(num_channel))
                                        {
                                            if(currentVersion>=2)
                                            {
                                                var port = json.port;
                                                var reason = res.reason;
                                                if( (reason >= 1 && reason <= 8 && port == 2) || (reason==1 && port == 5) ) 
                                                {
                                                    channel = storage.devices.get_channel(_device.devEui,reason);
                                                    var validChannel = channel!==undefined&&channel.name!==undefined;
                                                    if(validChannel&&channel.enable_danger)
                                                    {
                                                        if (channel.enable_danger)
                                                        {
                                                            storage.map_nav.set_history_danger(_device.devEui,reason,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                            storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                            channel.danger = true;
                                                        }
                                                        send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                    }
                                                    else
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                                var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                                if (validChannel)
                                                {
                                                    if (channel.name!==undefined)
                                                    {
                                                        if (res.type_package==2&&channel.enable_danger)
                                                        {
                                                            if (channel.enable_danger)
                                                            {
                                                                storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,channel.num_channel,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                                storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                                channel.danger = true;
                                                            }
                                                            send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                        }
                                                        else
                                                        {
                                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                        }
                                                    }
                                                    else
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 3:
                                        num_channel = res.num_channel!==undefined?parseInt(res.num_channel):false;
                                        if (num_channel!==false&&!isNaN(num_channel))
                                        {
                                            num_channel = num_channel + 6;
                                            channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                            var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                            if (validChannel)
                                            {
                                                if (channel.name!==undefined)
                                                {
                                                    if (res.type_package==2&&channel.enable_danger)
                                                    {
                                                        if (channel.enable_danger)
                                                        {
                                                            storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,channel.num_channel,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                            storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                            channel.danger = true;
                                                        }
                                                        send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                    }
                                                    else
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 4:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            {
                                                if ( storage.devices.devices_list[i].version == 1 )
                                                {
                                                    var checkEvent = res.reason!==0;
                                                    var t = parseFloat(res.temperature);
                                                    var checkTemperature = res.limit_exceeded;
                                                    if (checkEvent||checkTemperature)
                                                    {
                                                        if (channel.enable_danger)
                                                        {
                                                            storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                            storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                            channel.danger = true;
                                                        }   
                                                        send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                    }
                                                    else
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    } 
                                                } 
                                                else if( storage.devices.devices_list[i].version == 0 )
                                                {
                                                    var checkEvent = res.reason!==0;
                                                    var t = parseFloat(res.temperature);
                                                    var t_max = channel.max_t;
                                                    var t_min = channel.min_t;
                                                    var checkTemperature = t<=t_min||t>=t_max;
                                                    if (checkEvent||checkTemperature)
                                                    {
                                                        if (channel.enable_danger)
                                                        {
                                                            storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                            storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                            channel.danger = true;
                                                        }   
                                                        send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                    }
                                                    else
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 5:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            {
                                                if ( storage.devices.devices_list[i].version == 1 )
                                                {
                                                    var s = parseFloat(res.sensorTP);
                                                    var danger = res.reason != 0 && res.reason !=5;
                                                    if (channel.enable_danger && danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                        send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                    }
                                                    else
                                                    {
                                                         send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else if (storage.devices.devices_list[i].version == 0 )
                                                {
                                                    var s = parseFloat(res.sensorTP);
                                                    var dangerEvent = res.sensor_danger_1||res.sensor_danger_2?true:false;
                                                    var validValue = s!==undefined&&typeof s === 'number';
                                                    var sensorEvent = false;
                                                    var min = parseFloat(channel.min_normal_v);
                                                    var max = parseFloat(channel.max_normal_v);
                                                    var min_v = parseFloat(channel.min_v);
                                                    var max_v = parseFloat(channel.max_v);
                                                    if (validValue&&!isNaN(min)&&!isNaN(max)&&!isNaN(min_v)&&!isNaN(max_v))
                                                    {
                                                        if (s===0)
                                                        {
                                                            sensorEvent = true;
                                                        }
                                                        else if (s<=25&&s>=2)
                                                        {
                                                            var newvalue = scope.my_converter.parse4_20mA(s,min_v,max_v);
                                                            if (typeof newvalue === 'number')
                                                            {
                                                                if (newvalue<=min||newvalue>=max)
                                                                {
                                                                    sensorEvent = true;
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                           sensorEvent = true; 
                                                        }
                                                        var resVal = scope.get_value4_20mA(s);
                                                        if (resVal!=='Неизвестно')
                                                        {
                                                            if (resVal<=min||resVal>=max)
                                                            {
                                                                sensorEvent = true;
                                                            }
                                                        }
                                                    }
                                                    if (sensorEvent||dangerEvent)
                                                    {
                                                        if (channel.enable_danger)
                                                        {
                                                            storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                            storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                            channel.danger = true;
                                                        }
                                                        send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                    }
                                                    else
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 6:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.reason!==undefined&&parseInt(res.reason)!==0)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 7:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.reason!==undefined&&parseInt(res.reason)!==0)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 8:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.reason!==undefined&&parseInt(res.reason)!==0)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 9:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            {
                                                var checkEvent = res.state_display||res.leaking||res.breakthrough||res.hall_1;
                                                if (checkEvent)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 10:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.reason!==undefined&&parseInt(res.reason)!==0)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 14:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.alarm)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 12:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.type_package==1&&res.event!==undefined&&res.event!=1&&res.event!=19)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 13:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                var reason = res.reason!==undefined?parseInt(res.reason):NaN;
                                                if (!isNaN(reason)&&reason>0&&channel.enable_danger)
                                                {
                                                    storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                    storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                    channel.danger = true;
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 15:
                                        //TL11
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            {
                                                var checkEvent = res.reason!=='00';
                                                var t = parseFloat(res.temperature);
                                                var t2 = parseFloat(res.temperature_2);
                                                var t_max = channel.max_t;
                                                var t_min = channel.min_t;
                                                var checkTemperature = t<=t_min||t>=t_max;
                                                var checkTemperature2 = t2<=t_min||t2>=t_max;
                                                if (checkEvent||checkTemperature||checkTemperature2)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }   
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 17:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                var reason = res.reason!==undefined?parseInt(res.reason):NaN;
                                                if (!isNaN(reason)&&reason!=1&&channel.enable_danger)
                                                {
                                                    storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                    storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                    channel.danger = true;
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 18:
                                        if(currentVersion>=2)
                                        {
                                            var reason = res.reason;
                                            if(reason >= 1 && reason <= 4 ) 
                                            {
                                                channel = storage.devices.get_channel(_device.devEui,reason);
                                                var validChannel = channel!==undefined&&channel.name!==undefined;
                                                if(validChannel&&channel.enable_danger)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(_device.devEui,reason,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else if(reason == 5)
                                            {
                                                if(typeof _device.channels === 'object')
                                                {
                                                    var count = 0;
                                                    for(var key = 0; key <= _device.channels.length; key++)
                                                    {
                                                        channel = _device.channels[key];
                                                        var validChannel = channel!==undefined&&channel.name!==undefined;
                                                        if(validChannel&&channel.enable_danger)
                                                        {
                                                            storage.map_nav.set_history_danger(_device.devEui,channel.num_channel,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                            storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                            channel.danger = true;
                                                            send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                        }
                                                    }
                                                    if(count === 0)
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            num_channel = res.num_channel!==undefined?parseInt(res.num_channel):false;
                                            if (num_channel!==false&&!isNaN(num_channel))
                                            {
                                                channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                                var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                                if (validChannel)
                                                {
                                                    if (channel.name!==undefined)
                                                    {
                                                        if (res.type_package==2&&channel.enable_danger)
                                                        {
                                                            if (channel.enable_danger)
                                                            {
                                                                storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,channel.num_channel,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                                storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                                channel.danger = true;
                                                            }
                                                            send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                        }
                                                        else
                                                        {
                                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                        }
                                                    }
                                                    else
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        break;
                                    case 21:
                                        num_channel = res.num_channel!==undefined?parseInt(res.num_channel):false;
                                        if (num_channel!==false&&!isNaN(num_channel))
                                        {
                                            num_channel = num_channel + 10;
                                            channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                            var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                            if (validChannel)
                                            {
                                                if (channel.name!==undefined)
                                                {
                                                    if (res.type_package==5&&channel.enable_danger)
                                                    {
                                                        if (channel.enable_danger)
                                                        {
                                                            storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,channel.num_channel,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                            storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                            channel.danger = true;
                                                        }
                                                        send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                    }
                                                    else
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 20:
                                        num_channel = res.num_channel!==undefined?parseInt(res.num_channel):false;
                                        if (num_channel!==false&&!isNaN(num_channel))
                                        {
                                            num_channel = num_channel + 10;
                                            channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                            var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                            if (validChannel)
                                            {
                                                if (channel.name!==undefined)
                                                {
                                                    if (res.type_package==5&&channel.enable_danger)
                                                    {
                                                        if (channel.enable_danger)
                                                        {
                                                            storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,channel.num_channel,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                            storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                            channel.danger = true;
                                                        }
                                                        send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                    }
                                                    else
                                                    {
                                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                    }
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 23:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.reason!==undefined&&parseInt(res.reason)!==1)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;   
                                    case 24:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.type_package==1&&res.event!==undefined&&res.event!=1&&res.event!=19)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 25:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.reason!==undefined&&parseInt(res.reason)!==1)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;  
                                    case 26:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.reason!==undefined&&parseInt(res.reason)!==1)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break; 
                                    case 27:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.type_package==1&&res.event!==undefined&&res.event!=1&&res.event!=19)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 28:
                                        //распознаются только тревоги на основе причин
                                        if ( res.reason == 2 ) num_channel = 1;
                                        if ( res.reason == 3 ) num_channel = 2;
                                        if (num_channel!==false&&!isNaN(num_channel))
                                        {
                                            channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                            var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                            if ( validChannel && channel.name!==undefined )
                                            {
                                                if (channel.enable_danger)
                                                {
                                                    storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,channel.num_channel,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                    storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                    channel.danger = true;
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 30:
                                        num_channel = res.num_channel!==undefined?parseInt(res.num_channel):false;
                                        if (num_channel!==false&&!isNaN(num_channel))
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    case 31:
                                        num_channel = 1;
                                        channel = storage.devices.get_channel(storage.devices.devices_list[i].devEui,num_channel);
                                        var validChannel = channel!==undefined&&channel.num_channel!==undefined;
                                        if (validChannel)
                                        {
                                            if (channel.name!==undefined)
                                            { 
                                                if (res.reason!==undefined&&parseInt(res.reason)!==16&&parseInt(res.reason)!==9&&parseInt(res.reason)!==6)
                                                {
                                                    if (channel.enable_danger)
                                                    {
                                                        storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                                        storage.events.setEvent(res.time,json.ts,'danger',undefined,undefined,channel,_device,res);
                                                        channel.danger = true;
                                                    }
                                                    send_vega.logs.set_log('Сработала тревога',channel.name_level_1+' -> '+channel.level_2+' -> '+channel.name);
                                                }
                                                else
                                                {
                                                    send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                                }
                                            }
                                            else
                                            {
                                                send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                            }
                                        }
                                        else
                                        {
                                            send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')');
                                        }
                                        break;
                                    default:
                                        var otherInfo = '';
                                        var recommendedDT = scope.storage.type_device_list.get_type_device_on_appEui(json.appEui);
                                        if (recommendedDT)
                                        {
                                            otherInfo+=', предположительно '+recommendedDT.name;
                                        }
                                        send_vega.logs.set_log('Поступили новые данные',_device.devName + ' ('+_device.devEui+')'+otherInfo);
                                        break;
                                }
                            }
                            var validChannel = typeof channel == 'object' && channel.name;
                            var validHistory = typeof res == 'object';
                            
                            if(events_low_battery_charge && validChannel && validHistory)
                            {
                                var validCharge = typeof res.charge == 'number' && !isNaN(res.charge);
                                if(validCharge && res.charge<=10)
                                {
                                    storage.map_nav.set_history_danger(storage.devices.devices_list[i].devEui,1,channel.name_level_1,channel.address_level_1,channel.level_2);
                                    storage.events.setEvent(res.time,json.ts,'danger',`На устройстве ${channel.name} заряд батареи ${res.charge}%`,`Низкий заряд батареи!`,channel,_device,res);
                                    channel.danger = true;
                                }
                            }
                        }
                    }
                   var dataForselectedDevice = storage.devices.select_channel_temp.devEui == json.devEui;
                   if (dataForselectedDevice)
                   {
                       scope.showDataMap('rx');
                   }
                   storage.devices.get_statistics(storage.date_range);
                   scope.$apply(function (){ 
                       scope.storage;
                   })
                    return ok;
                }
                else
                {
                    send_vega.refrash_last_time_server(json.ts);
                    return false
                }
            }
            else
            {
                return false;
            }
            return true;
        }
        catch(err)
        {
            console.log(err);
            console.log('Error parse');
            return false;
        }
    }
    var my_ws = new WebSocket(ws.address);
    send_vega.status=false;
    send_vega.reload_status=false;
    my_ws.onopen=function (){
        send_vega.status=true;
        this.status=true;
        if (send_vega.auth_status){
            send_vega.send_get_device();
        }
        else
        {
            send_vega.token_auth_req();
            send_vega.loader_auth=true;
        }
        
     }
    my_ws.onclose=function(event){
        if (event.wasClean)
        {
        }
        else
        {
        }
        send_vega.auth_status=false;
        send_vega.status=false;
        if (!send_vega.reload_status)
        {
            $timeout(function (){ send_vega.reload_status=true; send_vega.reload();  },10000);
        }
        console.log('WebSocket закрыт');
    }
    my_ws.onerror=function(error){
       send_vega.loader_auth=false;
        send_vega.status=false;
        if (!send_vega.reload_status)
        {
            send_vega.reload_status=true;
            $timeout(function (){send_vega.reload()},10000);
        }
        console.log('WebSocket закрылся с ошибкой');
    }
    my_ws.onmessage=function(event){
       send_vega.last_time = new Date().getTime();
       parse_vega_api(event.data);
    };
   send_vega.reload = function ()
    {
        if (!send_vega.status)
        {
            try
            {
                my_ws.close();
            }
            catch(err)
            {
                
            }
            try
            {
                var new_ws = new WebSocket(ws.address);
                new_ws.onmessage=my_ws.onmessage;
                new_ws.onerror=my_ws.onerror;
                new_ws.onclose=my_ws.onclose;
                new_ws.onopen=my_ws.onopen;
                my_ws = new_ws;  
                
                send_vega.reload_status=false;
            }
            catch(err)
            {
                
            }
        }
        else
        {
            send_vega.reload_status=false;
            console.log('info 717');
        }

    };
    
    return send_vega;
}]);

app.controller('AppController',function(WS,storage,$scope,$rootScope,$timeout,leafletBoundsHelpers,leafletData,$mdSidenav,$mdDialog){
   

    $scope.loadPage = true;
    $scope.timezone = '';
    $scope.command_list_cookie = new command_list(); ;
    $scope.command_list_cookie.set_command_list_array(command_list_cookie);
    $scope.toggle_sticky = new sticky();
    $scope.WS = WS;
    $scope.multy_command = 0;
    $scope.count_data = 1;
    $scope.count_data_event = 1;
    $scope.count_data_energy = 1;
    $scope.count_data_energy_archive = 1;
    $scope.count_data_slices = 1;
    $scope.count_data_journals = 1;
    $scope.count_data_history = 1;
    $scope.count_data_instant = 1;
    $scope.count_data_instant2 = 1;
    $scope.count_data_info = 1;
    $scope.count_data_info2 = 1;
    $scope.showJournalType = -1;
    $scope.count_data_jp = 1;
    $scope.count_data_rl = 1;

    $scope.step_data=10;
    $scope.step_data_event=10;
    $scope.step_data_energy=10;
    $scope.step_data_energy_archive=10;
    $scope.step_data_slices=10;
    $scope.step_data_journals=1000;
    $scope.step_data_history=10;
    $scope.step_data_instant=10;
    $scope.step_data_instant2=10;
    $scope.step_data_info=10;
    $scope.step_data_info2=10;

    $scope.step_data_jp=10;
    $scope.step_data_rl=10;

    $scope.my_converter = new vega_converter();
    $scope.valid  = new valid_data();
    $scope.timezones = timezones;
    $scope.sortChannel = 'name';
    $scope.managerReport = new VegaReport(reportTypes);
    $scope.audio_danger = typeof audio_danger === 'boolean'?audio_danger:false;
    $scope.select_language = typeof select_language === 'boolean'?select_language:false;
    angular.extend($scope,{
        markers:new Object(),
        paths:new Object(),
        defaults:{
            minZoom:2,
            maxZoom:18,
            tileLayerOptions:{
                reuseTiles:false
            }
        },
		tiles: map_tiles_leaflet,
        controls:$scope.controls,
        maxBounds: {
                  southWest: {
                    lat: 90,
                    lng: -180
                  },
                  northEast: {
                    lat: -90,
                    lng: 180
                  }
                }
    });


    $scope.toggleRight = buildToggler('right');
    $scope.isOpenRight = function(){
      return $mdSidenav('right').isOpen();
    };



    function buildToggler(navID) {
      return function() {
        // Component lookup should always be available since we are not using `ng-if`
        $mdSidenav(navID)
          .toggle()
          .then(function () {
            // $log.debug("toggle " + navID + " is done");
          });
      };
    }

    $scope.universalAlert = function (message,title)
    {
        if(!title) title = 'Внимание!';
        $mdDialog.show(
            $mdDialog.alert()
              .clickOutsideToClose(true)
              .title(title)
              .textContent(message)
              .ariaLabel(title)
              .ok('Хорошо')
        );
    }
    /**
     * 
     * @param {*} title title
     * @param {*} message message
     * @param {*} successF function success
     * @param {*} cancelF function cancel
     */
    $scope.universalConfirm = function (title, message, successF, cancelF) {
        if ( !title ) title = 'Вы уверены?';
        if ( !message ) message = title;
        if ( !successF ) successF = ()=> { console.log(' universalConfirm success') };
        if ( !cancelF ) cancelF = ()=> { console.log(' universalConfirm cancel') };
        var confirm = $mdDialog.confirm()
          .title(title)
          .textContent(message)
          .ok('Хорошо')
          .cancel('Отмена');
        $mdDialog.show(confirm).then(successF, cancelF);
      };
    $scope.copy = function (str)
    {
        const el = document.createElement('textarea');
        el.value = str;
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);
    };
    $scope.getTextTypeJournal31 = function(num,index)
    {
        if(num==1)
        {
            if( index == 0 ) return 'Провалы напряжения (1,1)';
            if( index == 1 ) return 'Перенапряжения напряжений (1,2)';
            if( index == 2 ) return 'Отрицательные отклонения (1,3)';
        }
        else if(num==2)
        {
            if( index == 0 ) return 'Положительные отклонения (2,1)';
            if( index == 1 ) return 'Минимальное значение мгновенного напряжения  (2,2)';
            if( index == 2 ) return 'Максимальное значение мгновенного напряжения (2,3)';
        }
        return '';
    }
    $scope.parseTemperature = function(t)
    {
        if(t<=250)
        {
            return ((t/10)+20) + '°C' ;
        }
        else if(t == 251)
        {
            return 'Зарезервировано';
        }
        else if(t == 252)
        {
            return 'Меньше 20°C';
        }
        else if(t == 253)
        {
            return 'Больше 45°C';
        }
        else if(t == 254)
        {
            return 'Пустое значение';
        }
        else if(t == 255)
        {
            return 'Ошибка измерения температуры';
        }
        else
        {
            return 'Неизвестно';
        }
    }
    $scope.parseCodeModel = function(code)
    {
        // Трёхфазный ЦЭ2727A
        // 40 - 5(60) с реле
        // 41 - 5(60) без реле
        // 42 - 5(10) без реле
        // 43 - 10(100) без реле

        // Однофазный ЦЭ2727A
        // 20 - 5(60) с реле плоский
        // 25 - 5(60) с реле DIN рейка
        if(code==0x40) return 'ЦЭ2727A, Трёхфазный, 5(60), с реле';
        else if(code==0x41) return 'ЦЭ2727A, Трёхфазный, 5(60), без реле';
        else if(code==0x42) return 'ЦЭ2727A, Трёхфазный, 5(10), без реле';
        else if(code==0x43) return 'ЦЭ2727A, Трёхфазный, 10(100), без реле';
        else if(code==0x20) return 'ЦЭ2727A, Однофазный, 5(60), с реле плоский';
        else if(code==0x25) return 'ЦЭ2727A, Однофазный, 5(60), с реле DIN рейка';
        
        return 'Неизвестный код ('+code+')';
    }
    $scope.parseCodeReasonRelay = function (code)
    {
        if(code==0x00) return 'Команда вкл/выкл через интерфейс RS-485';
        else if(code==0x01) return 'Команда вкл/выкл через оптопорт';
        else if(code==0x1F) return 'Включение кнопкой на приборе';
        else if(code==0x20) return 'Выключение в результате измерения на заданном интервале';
        else if(code==0x21) return 'Выключение в результате измерения на получасовом интервале';
        else if(code==0x22) return 'Включение реле с наступлением новых суток, если включен режим автовключения';
        else if(code==0x23) return 'Включение реле через заданный интервал, если включен режим автовключения';
        else if(code==0x24) return 'Включение реле при инициализации режима работы реле или при обнаружении ошибки самодиагностики.';
        return 'Неизвестный код ('+code+')';
    }
    $scope.getVersions = function ()
    {
        var device = this.editDevice.device;
        if(device)
        {
           var typeDevice = storage.type_device_list.get_type_device(device.device_type);
            var versions = typeDevice.versions;
            if( isObject(versions) && isObject(versions.list) )
            {
                return versions.list;
            } 
        }
        return {};
    }
    $scope.showLastStateTamper = function()
    {
        
        var validTypeChannel = isObject(this.editDevice.type_channel) && this.editDevice.type_channel.type;
        var validDevice = isObject(this.editDevice.device) && this.editDevice.device.devEui;

        var idTypeChannel = storage.devices.select_channel_temp.type_channel;
        var typeChannel = storage.type_channel_list.get_type_channel(idTypeChannel);
        var device = storage.devices.select_channel_temp._self;
        var validDevice = isObject(device);
        var validTypeChannel = isObject(typeChannel);
        if( validTypeChannel && validDevice )
        {
            var type = typeChannel.type;
            var dt = device.device_type;
            if ( type == 3 )  return true; //td11
            if ( type == 8 && dt != 17 ) return true; //ug(gm2)
            if ( type == 11 ) return true; //tl11
        }
        return false;
    }
    $scope.showEnableDanger = function()
    {
        var validTypeChannel = isObject(this.editDevice.type_channel) && this.editDevice.type_channel.type;
        var validDevice = isObject(this.editDevice.device) && this.editDevice.device.devEui;
        if( validDevice && validTypeChannel )
        {
            var type = this.editDevice.type_channel.type;
            var dt = this.editDevice.device.device_type;
            var version = this.editDevice.device.version;
            var currentVersion = -1;
            if( version !== undefined ) version = parseInt(version);
            if(!isNaN(version)) currentVersion = version;

            var si21_22 = dt == 11 || dt == 18;
            var si21_22rev3 = si21_22 && currentVersion >= 2;
            var s12rev2 = dt == 2 && currentVersion >= 2;

            if ( type == 2 ) return true; //охранный канал
            if ( type == 20 )  return true; //M-BUS-1 и M-BUS-2
            if ( dt == 4 )   return true; //TD-11
            if ( dt == 5 )   return true; //ТП-11
            if ( dt == 6 )   return true; //SMART МС-0101
            if ( dt == 7 )   return true; //SMART AS-0101
            if ( dt == 8 )   return true; //SMART MS-0101
            if ( dt == 9 )   return true; //Водосчетчик SVE
            if ( dt == 10 )  return true; //SMART SS-0101
            //if ( dt == 11 )  return true; //CИ-21
            if ( dt == 12 )  return true; //Электросчетчик/УЭ
            if ( dt == 13 )  return true; //GM-2
            if ( dt == 14 )  return true; //LM-1
            if ( dt == 15 )  return true; //TL-11
            if ( dt == 17 )  return true; //GM-1
            if ( dt == 23 )  return true; //SMART HS-0101
            if ( dt == 24 )  return true; //Электросчетчик/спббзип
            if ( dt == 25 )  return true; //SMART UM-0101
            if ( dt == 26 )  return true; //SRC
            if ( dt == 27 )  return true; //Электросчетчик/merc
            if ( si21_22rev3 ) return true; // si21 si22 с прошивкой старше 2.2 
            if ( dt == 31 )  return true; //SMART SS-0102
            if ( s12rev2 ) return true; //si12 с прошивкой ревизии 2
        }
        return false;
    }
    $scope.showLastDate = function()
    {
        var validTypeChannel = isObject(this.editDevice.type_channel) && this.editDevice.type_channel.type;
        var validDevice =  isObject(this.editDevice.device) && this.editDevice.device.devEui;
        if( validDevice && validTypeChannel )
        {
            var type = this.editDevice.type_channel.type;
            var dt = this.editDevice.device.device_type;
            if ( type == 1 )  return true; //Импульсные входа
            if ( type == 4 ) return true; //Водосчетчик SVE
            if ( type == 7 ) return true; //Электросчетчик/УЭ
            if ( type == 8 ) return true; //GM-2
            if ( type == 9 ) return true; //Si-13 Электросчетчик меркурий
            if ( type == 20 )  return true; //M-BUS-1 и M-BUS-2
        }
        return false;
    };
    $scope.showCalibInterval = function()
    {
        var validTypeChannel = isObject(this.editDevice.type_channel) && this.editDevice.type_channel.type;
        var validDevice = isObject(this.editDevice.device) && this.editDevice.device.devEui;
        if( validDevice && validTypeChannel )
        {
            var type = this.editDevice.type_channel.type;
            var dt = this.editDevice.device.device_type;
            if ( type == 1 )  return true; //Импульсные входа
            if ( type == 4 ) return true; //Водосчетчик SVE
            if ( type == 7 ) return true; //Электросчетчик/УЭ
            if ( type == 8 ) return true; //GM-2
            if ( type == 9 ) return true; //Si-13 Электросчетчик меркурий
            if ( type == 20 )  return true; //M-BUS-1 и M-BUS-2
        }
        return false;
    };
    $scope.showPersonalNum = function()
    {
        var validTypeChannel = isObject(this.editDevice.type_channel) && this.editDevice.type_channel.type;
        var validDevice = isObject(this.editDevice.device) && this.editDevice.device.devEui;
        if( validDevice && validTypeChannel )
        {
            var type = this.editDevice.type_channel.type;
            var dt = this.editDevice.device.device_type;
            if ( type == 1 )  return true; //Импульсные входа
            if ( type == 4 ) return true; //Водосчетчик SVE
            if ( type == 7 ) return true; //Электросчетчик/УЭ
            if ( type == 8 ) return true; //GM-2
            if ( type == 9 ) return true; //Si-13 Электросчетчик меркурий
            if ( type == 20 )  return true; //M-BUS-1 и M-BUS-2
        }
        return false;
    };
    $scope.changeTypeMeter = function ()
    {
        var tm = this.editDevice.type_meter;
        if((this.editDevice.ia === '' || this.editDevice.ia === undefined) && tm == 5 ) this.editDevice.ia = 1;
    }
    $scope.showIA = function()
    {
        var validTypeChannel = isObject(this.editDevice.type_channel) && this.editDevice.type_channel.type;
        var validDevice = isObject(this.editDevice.device) && this.editDevice.device.devEui;
        if( validDevice && validTypeChannel )
        {
            var type = this.editDevice.type_channel.type;
            var dt = this.editDevice.device.device_type;
            if ( type == 7 ) return true; //Электросчетчик/УЭ
            if ( type == 9 ) return true; //Si-13 Электросчетчик меркурий
            if ( type == 20 )  return true; //M-BUS-1 и M-BUS-2
            if ( type == 22 ) return true; //Si-13 Modbus
            // if ( type == 30 ) return true; //Therm
        }
        return false;
    };
    $scope.checkMultipleVersions = function ()
    {
        var device = this.editDevice.device;
        if(device)
        {
            var typeDevice = device.device_type;
            return storage.type_device_list.checkMultipleVersions(typeDevice);
        }
        return false;
    }
    $scope.paramIntToDisplay = function (value)
    {
        if(!isNaN(value)) return value;
        return ' - ';
    }
    $scope.validAvgTemperatureSelectedDevice = function ()
    {
        var device = storage.devices.select_channel_temp;
        var avgTemperatur = device.statistics.avgTemperatur;
        return !isNaN(avgTemperatur)&&avgTemperatur!==false;
    }
    $scope.checkSettingDevice = function () 
    {
        var device = storage.devices.select_channel_temp;
        var validDevice = device&&device._self;
        if (!validDevice) 
        {
            return false;
        }
        var deviceType = device._self.device_type;
        var deviceVersion = device._self.version;
        if (deviceType !== undefined)
        {
            deviceType = parseInt(deviceType);
        }
        else
        {
            return false;
        }
        var settings = storage.type_device_list.get_settings_type_device(deviceType,deviceVersion);
        var validSettings = settings !== undefined && settings.length > 0;
        if (validSettings === true)
        {
            return true;
        }
        return false;
    }
    $scope.checkInfoDevice = function () 
    {
        var device = storage.devices.select_channel_temp;
        var validDevice = device&&device._self;
        if (!validDevice) 
        {
            return false;
        }
        var deviceType = device._self.device_type;
        var deviceVersion = device._self.version;
        if (deviceType !== undefined)
        {
            deviceType = parseInt(deviceType);
        }
        else
        {
            return false;
        }
        var info = storage.type_device_list.get_info_type_device(deviceType,deviceVersion);
        var validInfo = typeof info === 'boolean';
        if (validInfo === true)
        {
            return info;
        }
        return false;
    }
    $scope.checkDiagnosticDevice = function () 
    {
        var device = storage.devices.select_channel_temp;
        var validDevice = device&&device._self;
        if (!validDevice) 
        {
            return false;
        }
        var deviceType = device._self.device_type;
        var deviceVersion = device._self.version;
        if (deviceType !== undefined)
        {
            deviceType = parseInt(deviceType);
        }
        else
        {
            return false;
        }
        var diagnostic = storage.type_device_list.get_diagnostic_type_device(deviceType,deviceVersion);
        var validDiagnostic = typeof diagnostic === 'boolean';
        if (validDiagnostic === true)
        {
            return diagnostic;
        }
        return false;
    }
    $scope.checkValidSettingsParamDevice = function (param, value) 
    {
        var device = storage.devices.select_channel_temp;
        var validDevice = device&&device._self;
        if (!validDevice) 
        {
            return false;
        }
        var deviceType = device._self.device_type;
        var deviceVersion = device._self.version;
        if (deviceType !== undefined)
        {
            deviceType = parseInt(deviceType);
        }
        else
        {
            return false;
        }
        var settingsValues = storage.type_device_list.get_settingsValues_type_device(deviceType,deviceVersion);
        var validSettingsValues = typeof settingsValues === 'object';
        if (validSettingsValues === true)
        {
            var validParam = typeof settingsValues[param] == 'object';
            if(!validParam) return true;

            return settingsValues[param].indexOf(value) != -1 ;
        }
        else
        {
            return true;
        }
        return false;
    }
    $scope.sendRequestInfo = function (device)
    {
        var validSelectedDevice = storage.devices.select_channel_temp!==undefined&& isObject(storage.devices.select_channel_temp._self) ;
        if (device===undefined&&validSelectedDevice) 
        {
            device = storage.devices.select_channel_temp._self;
        }
        WS.send_data('01',device.devEui,true,195);
    }
    $scope.sendRequestDiagnostic = function (device)
    {
        var validSelectedDevice = storage.devices.select_channel_temp!==undefined&&isObject(storage.devices.select_channel_temp._self) ;
        if (device===undefined&&validSelectedDevice) 
        {
            device = storage.devices.select_channel_temp._self;
        }
        WS.send_data('01',device.devEui,true,85);
    }
    $scope.sendRequestSettings = function (device)
    {
        var validSelectedDevice = storage.devices.select_channel_temp!==undefined&& isObject(storage.devices.select_channel_temp._self) ;
        if (device===undefined&&validSelectedDevice) 
        {
            device = storage.devices.select_channel_temp._self;
        }
        WS.send_data('01',device.devEui,true,3);
    }
    $scope.sendSettings = function (device)
    {
        var validParamsSettings = this.checkValidParamsSettings();
        if (validParamsSettings)
        {
            var validSelectedDevice = storage.devices.select_channel_temp!==undefined&& isObject(storage.devices.select_channel_temp._self);
            if (device===undefined&&validSelectedDevice) 
            {
                device = storage.devices.select_channel_temp._self;
            }
            if ( isObject(device) && isObject(device.tempSettings) )
            {
                var settings = storage.type_device_list.get_settings_type_device(device.device_type,device.version);
                var hexSettings = device.getHexTempSettings(storage.devices.select_channel_temp,settings);
                if (hexSettings)
                {
                    WS.send_data(hexSettings,device.devEui,true,3);
                }
                else
                {
                    this.universalAlert('Не удалось отправить настройки. Ошибка 13523.','Ошибка!');
                }
            }
        }
        else
        {
            this.universalAlert('Ошибка при отправке настроект на устройство, все поля должны быть заполнены. Проверьте корректность введенных Вами данных. ');
        }
    }
    $scope.getCurrentTime=function ()
    {
        return new Date().getTime();
    }
    $scope.getDeviceEditorInfo = function ()
    {
        var result = '';
        if (this.editDevice.level_1.name_level_1!==undefined) result+='<b>Название Объекта:</b> '+this.editDevice.level_1.name_level_1+'<br>';
        if (this.editDevice.level_1.address_level_1!==undefined) result+='<b>Адрес Объекта:</b> '+this.editDevice.level_1.address_level_1+'<br>';
        if (this.editDevice.level_2!==undefined) result+='<b>Помещение:</b> '+this.editDevice.level_2+'<br>';
        if (this.editDevice.name!==undefined) result+='<b>Название прибора:</b> '+this.editDevice.name+'<br>';
        if (this.editDevice.status!==undefined) result+='<b>Состояние устройства:</b> '+storage.status_channel_list.get_status(this.editDevice.status)+'<br>';
        if (this.editDevice.info_channel!==undefined) result+='<b>Описание устройства:</b> '+this.editDevice.info_channel+'<br>';
        if (storage.edit_device_main.devEui!==undefined) result+='<b>DevEui радиомодема:</b> '+storage.edit_device_main.devEui+'<br>';
        if (storage.edit_device_main.devName!==undefined) result+='<b>Имя радиомодема:</b> '+storage.edit_device_main.devName+'<br>';
        if (storage.edit_device_main.selected_device_type==storage.edit_device_main.device_type) result+='<b>Модель радиомодема:</b> '+storage.type_device_list.get_type_device(storage.edit_device_main.device_type).name+'<br>';
        return result;
    }
    $scope.showTrack = function(event)
    {
        var track = new Object();
        track=$scope.storage.devices.getPointsMapsSelectedDevice(this.mapMode);
        angular.extend($scope,track);
//        var countOldMarkers= Object.keys(this.markers).length;
        var emptyPaths = !this.coordinates||this.coordinates.length===0;
        if (event=='click'||emptyPaths)
        {
            $scope.fitBounds(this.coordinates);
        }
    }
    $scope.showMarkers = function(event)
    {
        var markers = new Object();
        markers=$scope.storage.devices.getPointsMapsSelectedDevice(this.mapMode); 
        var countOldMarkers= Object.keys(this.markers).length;
        angular.extend($scope,{
            markers:markers
        });
        if (event=='click'||countOldMarkers<=0)
        {
            $scope.fitBounds(markers);
        }
    };
    $scope.fitBounds = function (points)
    {
        var my_bounds = new Array();
        for (var key in points)
        {
            my_bounds.push([points[key].lat,points[key].lng]);
        }
        leafletData.getMap().then(function(map) {
            setTimeout(function (){
               if (my_bounds.length>0)
                {
                    map.fitBounds(my_bounds);
                }
            },1000);
        });
    }
    $scope.selectMapMode = function(mode)
    {
        if (!this.checkButtonMap(mode)) return false;
        var clearOld = false;
        if (this.mapMode!=mode) clearOld = true;
        this.mapMode = mode;
        $scope.showDataMap('click',clearOld);
    }
    $scope.showDataMap = function(event,clearOld)
    {
        if ($scope.storage.devices.select_channel_temp.type_channel!==17 && $scope.storage.devices.select_channel_temp.type_channel!== 26) return;
        if (!this.mapMode) this.mapMode = 'last';
        if (clearOld)
        {
           this.clearMap(); 
        }
        if (this.mapMode=='track')
        {
            $scope.showTrack(event);
        }
        else
        {
            $scope.showMarkers(event);
        }
    }
    $scope.checkAvailabilityParamSettings = function( paramsSettings, deviceType, version)
    {
        var validSelectedDevice = storage.devices.select_channel_temp !== undefined && isObject(storage.devices.select_channel_temp._self);
        var settings = [];
        
        if ( deviceType === undefined && validSelectedDevice ) 
        {
            deviceType = storage.devices.select_channel_temp._self.device_type;
        }
        if ( version === undefined && validSelectedDevice ) 
        {
            version = storage.devices.select_channel_temp._self.version;
        }
        if ( deviceType !== undefined )
        {
            settings = storage.type_device_list.get_settings_type_device( deviceType, version );
        }
        if ( isObject(settings) )
        {
            if ( isObject(paramsSettings) )
            {
                for ( var i = 0; i < paramsSettings.length; i++ )
                {
                    var param = paramsSettings[i];
                    if ( settings.indexOf( param ) > -1 ) 
                    {
                        return true;
                    }
                }
            }
            else if ( typeof paramsSettings == 'number' )
            { 
                var param = paramsSettings;
                if ( settings.indexOf( param ) > -1 )
                {
                    return true;
                }
            }
        }
        return false;
    }
    $scope.validParamSettings = function(id,value)
    {
        switch (id) {
            case 1:
                return value >= 1 && value <= 11;
                break;
            case 3:
                return value === 1 || value === 2;
                break;
            case 4:
                return value === 1 || value === 2;
                break;
            case 5:
                return value === 1 || value === 2;
                break;
            case 8:
                return value >= 1 && value <= 15 && Number.isInteger( value );
                break;
            case 12:
                return value === 1 || value === 2;
                break;
            case 13:
                return value === 1 || value === 2;
                break;
            case 14:
                return value === 1 || value === 2;
                break;
            case 15:
                return value === 1 || value === 2;
                break;
            case 16:
                return value >= 1 && value <= 7 && Number.isInteger( value );
                break;
            case 22:
                return value >= 0 && Number.isInteger( value );
                break;
            case 33:
                return value >= 0 && value <= 10 && Number.isInteger( value );
                break;
            case 38:
                return value >= 1 && value <= 4 && Number.isInteger( value );
                break;
            case 39:
                return value >= 1 && value <= 4 && Number.isInteger( value );
                break;
            case 44:
                return value >= 1 && value <= 4 && Number.isInteger( value );
                break;
            case 45:
                return value >= 1 && value <= 60 && Number.isInteger( value );
                break;
            case 46:
                return value >= 1 && value <= 8 && Number.isInteger( value );
                break;
            case 48:
                return value >= 1 && value <= 255 && Number.isInteger( value );
                break;
            case 49:
                return value >= 1 && value <= 8 && Number.isInteger( value );
                break;
            case 50:
                    if ( !isObject(value) || value.length != 3 ) return false;
                    if ( !Number.isInteger( value[0] ) || !Number.isInteger( value[1] ) || !Number.isInteger( value[2] ) ) return false;
                    if ( value[0] < 0 || value[0] > 6 ) return false;
                    if ( value[1] < 0 || value[1] > 7 ) return false;
                    if ( value[2] < 0 || value[2] > 28 ) return false;
                    return true;
                break;
            case 51:
                // return value >= 1 && value <= 24 && Number.isInteger( value );
                    if ( !isObject(value) || value.length != 3 ) return false;
                    if ( !Number.isInteger( value[0] ) || !Number.isInteger( value[1] ) || !Number.isInteger( value[2] ) ) return false;
                    if ( value[0] < 0 || value[0] > 6 ) return false;
                    if ( value[1] < 0 || value[1] > 7 ) return false;
                    if ( value[2] < 0 || value[2] > 28 ) return false;
                    return true;
                break;
            case 52:
                    if ( !isObject(value) || value.length != 3 ) return false;
                    if ( !Number.isInteger( value[0] ) || !Number.isInteger( value[1] ) || !Number.isInteger( value[2] ) ) return false;
                    if ( value[0] < 0 || value[0] > 6 ) return false;
                    if ( value[1] < 0 || value[1] > 7 ) return false;
                    if ( value[2] < 0 || value[2] > 28 ) return false;
                    return true;
                break;
            case 53:
                return value===0 || value===1;
                break;
            case 54:
                return value >= 0 && Number.isInteger( value );
                break;
            case 55:
                return value >= -720 && value <= 840 && Number.isInteger( value );
                break;
            case 62:
                return value >= 1 && value <= 8 && Number.isInteger( value );
                break;
            case 63:
                return value >= 1 && value <= 7 && Number.isInteger( value );
                break;
            case 71:
                return value===1 || value===2;
                break;
            case 72:
                return value===0 || value===1;
                break;
            case 78:
                return value >= 1 && value <= 7 && Number.isInteger( value );
                break;
            case 79:
                return value === 0 || value === 1;
                break;
            case 80:
                return value >= -127 && value <= 127 && Number.isInteger( value );
                break;
            case 81:
                return value >= -127 && value <= 127 && Number.isInteger( value );
                break;
            case 84:
                return value >= 0 && Number.isInteger( value );
                break;
            case 85:
                return value >= 200 && value <= 2500 && Number.isInteger( value );
                break;
            case 86:
                return value >= 200 && value <= 2500 && Number.isInteger( value );
                break;
            case 88:
                return value >= 0 && Number.isInteger( value ) && value <= 100;
                break;
            case 89:
                return value >= 0 && Number.isInteger( value ) && value <= 100;
                break;
            case 114:
                return value >= 1 && value <= 24;
                break;

            case 115:
                return value >= 0 && Number.isInteger( value ) && value <= 110;
                break;
            case 116:
                return value >= 40 && Number.isInteger( value ) && value <= 110;
                break;
            case 117:
                return value >= 10 && Number.isInteger( value ) && value <= 10000;
                break;
            case 118:
                return value >= 10 && Number.isInteger( value ) && value <= 10000;
                break;
            case 119:
                return value >= 0 && Number.isInteger( value ) && value <= 2000;
                break;
            case 120:
                return value >= 0 && Number.isInteger( value ) && value <= 2000;
                break;

            case 124:
                return value >= 0 && value <= 1;
                break;
            case 126:
                return value >= 1 && value <= 15 && Number.isInteger( value );
                break;
            default:
                return value !== undefined;
                break;
        }
        return false;
    }
    $scope.defaultParamSetting = function(id)
    {
        var param = {};
        if( id === 50 || id === 51 || id === 52 )
        {
            param.value = new Array();
        }
        return param;
    }
    $scope.checkValidParamsSettings = function ( idParamSettings, device )
    {
        var settings = [];
        var validSelectedDevice = storage.devices.select_channel_temp!==undefined&& isObject(storage.devices.select_channel_temp._self);
        if (device===undefined&&validSelectedDevice) 
        {
            device = storage.devices.select_channel_temp._self;
        }
        if ( isObject(device) && isObject(device.tempSettings) )
        {
            if (idParamSettings)
            {
                if ( !isObject(device.tempSettings.params) )
                {
                    device.tempSettings.params = new Object();
                }
                if ( !isObject(device.tempSettings.params[idParamSettings]) )
                {
                    device.tempSettings.params[idParamSettings] = this.defaultParamSetting(idParamSettings);
                }
                var value = device.tempSettings.params[idParamSettings].value;
                return this.validParamSettings(idParamSettings,value);
            }
            else if ( device.device_type !== undefined )
            {
                  settings = storage.type_device_list.get_settings_type_device( device.device_type, device.version );
            }
            if ( isObject(settings) )
            {
                for (var i = 0; i < settings.length; i++)
                {
                    var idParamSettings = settings[i];
                    if ( !isObject(device.tempSettings.params) )
                    {
                        device.tempSettings.params = new Object();
                    }
                    if ( !isObject(device.tempSettings.params[idParamSettings]) )
                    {
                        device.tempSettings.params[idParamSettings] = this.defaultParamSetting(idParamSettings);
                    }
                    var value = device.tempSettings.params[idParamSettings].value;
                    if (!this.validParamSettings(idParamSettings,value))
                    {
                        return false;
                    }
                }
                return true;
            }
        }
        return false;
    }
    
    $scope.clearMap = function ()
    {
        angular.extend($scope,{
            markers:new Object(),
            paths:new Object(),
            decorations:new Object(),
            coordinates:new Array()
        });
    }
    $scope.checkButtonMap = function(mode)
    {
        var channel = storage.devices.select_channel_temp;
        var statistics = channel.statistics;
        if (!channel||!statistics) return false;
        var lastLocation = statistics.last_coordinate;
        var validLastLocation = lastLocation&&lastLocation.time;
        if (mode=='last'&&validLastLocation)  return true;
        var history = channel.history;
        if (channel&&history&&history.length>0)
        {
            var countValidLocations = 0;
            for (var i = 0; i<history.length; i++)
            {
                var item = history[i];
                if (item.coord_status) countValidLocations++;
                if (mode=='all'&&countValidLocations>0) return true;
            }
            if (mode=='track'&&countValidLocations>1) return true;
        }
        return false;
    }
    $scope.refreshSettingsSelectedDevice = function ()
    {
        if ( !isObject(storage.devices.select_channel_temp) )
        {
            storage.devices.select_channel_temp = new Object();
        }
        var dev = storage.devices.select_channel_temp._self;
        if (dev===undefined)
        {
            dev = new device();
        }
        else
        {
            WS.statusRequestSetting = true;
            WS.send_get_device_data_req(dev.devEui,undefined,undefined,1,3);
        }
        dev.refreshTempSetting();
        return true;
    }
    $scope.refreshInfoSelectedDevice = function ()
    {
        if ( !isObject(storage.devices.select_channel_temp) )
        {
            storage.devices.select_channel_temp = new Object();
        }
        var dev = storage.devices.select_channel_temp._self;
        if (dev===undefined)
        {
            dev = new device();
        }
        else
        {
            WS.statusRequestInfo = true;
            WS.send_get_device_data_req(dev.devEui,undefined,undefined,1,195);
        }
        return true;
    }
    $scope.refreshDiagnosticSelectedDevice = function ()
    {
        if ( !isObject(storage.devices.select_channel_temp) )
        {
            storage.devices.select_channel_temp = new Object();
        }
        var dev = storage.devices.select_channel_temp._self;
        if (dev===undefined)
        {
            dev = new device();
        }
        else
        {
            WS.statusRequestDiagnostic = true;
            WS.send_get_device_data_req(dev.devEui,undefined,undefined,1,85);
        }
        return true;
    }
    $scope.showSettingsDevice = function ()
    {
        $scope.device_page = 1;
        //$('#settingsDevice').modal('show');
        if ( !isObject(storage.devices.select_channel_temp) )
        {
            storage.devices.select_channel_temp = new Object();
        }
        var dev = storage.devices.select_channel_temp._self;
        if (dev===undefined)
        {
            dev = new device();
        }
        else
        {
            WS.statusRequestSetting = true;
            WS.send_get_device_data_req(dev.devEui,undefined,undefined,1,3);
        }
        dev.refreshTempSetting();
        return true;
    }
    $scope.showDiagnosticDevice = function ()
    {
        $scope.device_page = 2;
        if ( !isObject(storage.devices.select_channel_temp) )
        {
            storage.devices.select_channel_temp = new Object();
        }
        var dev = storage.devices.select_channel_temp._self;
        if (dev===undefined)
        {
            dev = new device();
        }
        else
        {
            WS.statusRequestDiagnostic = true;
            WS.send_get_device_data_req(dev.devEui,undefined,undefined,1,85);
        }
        return true;
    }
    $scope.showInfoDevice = function ()
    {
        $scope.device_page = 3;
        if ( !isObject(storage.devices.select_channel_temp) )
        {
            storage.devices.select_channel_temp = new Object();
        }
        var dev = storage.devices.select_channel_temp._self;
        if (dev===undefined)
        {
            dev = new device();
        }
        else
        {
            WS.statusRequestInfo = true;
            WS.send_get_device_data_req(dev.devEui,undefined,undefined,1,195);
        }
        return true;
    }
    $scope.getLogin = function ()
    {
        var login = get_cookie('login');
        if (login)
        {
            return login;
        }
        else
        {
            return '';
        }
    }
    $scope.modbus = function(bytes)
    {
        return bytes.join('');
    }
    $scope.selectInterface = function ( channel )
    {
        if ( !( channel.type_channel && channel.status !== undefined ) )
        {
            this.editDevice.num_channel = channel.num_channel;
            var si13 = this.editDevice.device.device_type == 3;
            var sh02 = this.editDevice.device.device_type == 28;
            var merc = si13 && channel.num_channel <= 6;
            var modBus = si13 && channel.num_channel > 8;
            var mbus1 = this.editDevice.device.device_type == 20;
            var mbus2 = this.editDevice.device.device_type == 21;
            var thermo = this.editDevice.device.device_type == 30;
            var mbus1_bus = mbus1 && channel.num_channel <= 10;
            if ( merc )
            {
                $scope.editDevice.type_channel = storage.type_channel_list.get_type_channel( 16 )
            }
            else if ( modBus )
            {
                $scope.editDevice.type_channel = storage.type_channel_list.get_type_channel( 22 )
            }
            else if (  mbus1_bus  || mbus2 == 21 )
            {
                $scope.editDevice.type_channel = storage.type_channel_list.get_type_channel( 20 );
            }
            else if ( mbus1 )
            {
                $scope.editDevice.type_channel = storage.type_channel_list.get_type_channel( 6 );
            }
            else if(thermo)
            {
                $scope.editDevice.type_channel = storage.type_channel_list.get_type_channel( 30 );
            }
        }
    }
    $scope.showOptionTypeChannel = function(channel,typeChannel)
    {
        var dt = parseInt(this.editDevice.device.device_type);
        if ((dt==1||dt==11||dt==2||dt==18||dt==30)&&typeChannel.device_type.indexOf(dt)>-1)
        {
            return true;
        }
        else if (dt==28&&typeChannel.device_type.indexOf(dt)>-1)
        {
            var channelDigital  = channel.num_channel == 1 || channel.num_channel == 2;
            var channelAnalogue = channel.num_channel == 3 || channel.num_channel == 4;
            var channelInterface = channel.num_channel == 5;

            var typeModBus    = typeChannel.id == 22;
            var type1Wire     = typeChannel.id == 28;
            var typeAnalogue  = typeChannel.id == 29;
            if( channelDigital && !typeModBus && !type1Wire && !typeAnalogue )
            {
                return true;
            }
            else if( channelAnalogue && typeAnalogue )
            {
                return true;
            }
            else if( channelInterface && ( typeModBus || type1Wire ) )
            {
                return true;
            }
        }
        else if (dt==3&&typeChannel.device_type.indexOf(dt)>-1)
        {
            if (channel.num_channel > 6 && channel.num_channel <=8 && typeChannel.id!=16 && typeChannel.id!=22 )
            {
                return true;
            }
            else if ( channel.num_channel > 8 && typeChannel.id!=16  && typeChannel.id==22)
            {
                return true;
            }
            else if (channel.num_channel<=6&&typeChannel.id==16 && typeChannel.id!=22)
            {
                return true;
            }
        }
        else if ( ( dt == 21 ) && typeChannel.device_type.indexOf(dt)>-1 )
        {
            return true;
        }
        else if ( ( dt == 20 || dt == 21 ) && typeChannel.device_type.indexOf(dt)>-1 )
        {
            if ( channel.num_channel > 10 && typeChannel.id != 20 )
            {
                return true;
            }
            else if ( channel.num_channel <= 10 && typeChannel.id == 20 )
            {
                return true;
            }
        }
        return false;
    }
    $scope.getNameTypeInterface = function(channel,typeDevice)
    {
        switch (typeDevice.id) {
            case 1:
                    return 'Канал '+channel.num_channel;
                break;
            case 2:
                return 'Канал '+channel.num_channel;
                break;
            case 18:
                return 'Канал '+channel.num_channel;
                break;
            case 11:
                    return 'Канал '+channel.num_channel;
                break;  
            case 3:
                   var number = 0;
                   if (channel.num_channel<=6)
                   {
                       number = channel.num_channel;
                       return 'Шина №'+number;
                   }
                   else if(channel.num_channel<=8)
                   {
                       number = channel.num_channel-6;
                       return 'Канал '+number;
                   }
                   else
                   {
                    number = channel.num_channel - 8;
                    return 'mod bus №'+number;
                   }
                break;
            case 20:
                var number = 0;
                if (channel.num_channel<=10)
                {
                    number = channel.num_channel;
                    return 'Шина №'+number;
                }
                else
                {
                    number = channel.num_channel-10;
                    return 'Канал '+number;
                }
                break;
            case 21:
                return 'Шина № '+channel.num_channel;
                break; 
            case 28:
                if (channel.num_channel == 1) return 'Цифровой №1';
                else if (channel.num_channel == 2) return 'Цифровой №2';
                else if (channel.num_channel == 3) return 'Аналоговый №1';
                else if (channel.num_channel == 4) return 'Аналоговый №2';
                else if (channel.num_channel == 5) return 'Интерфейс';
                break;
            default:
                return 'Интерфейс';
                break;
        }
    }
    $scope.editFilterDevices = function ()
    {   
            var filter = storage.map_nav.filterDevices;
            var listObject = storage.map_nav.list;
            for (var objKey in listObject)
            {
                var obj = listObject[objKey];
                if (obj.valid()&&filter)
                {
                    for (var roomKey in obj.list)
                    {
                        var room = obj.list[roomKey];
                        if (room.valid()&&filter)
                        {
                            room._check = true;
                        }
                        else
                        {
                            room._check  = false;
                        }
                    }
                    obj._check=true;
                }
                else
                {
                    for (var roomKey in obj.list)
                    {
                        obj.list[roomKey]._check = false;
                    }
                    obj._check=false;
                }
            }
            $scope.selectLevelSelectedChannel();
    }
    $scope.selectLevelSelectedChannel = function ()
    {
        var listObject = storage.map_nav.list;
        for (var keyObj in listObject)
        {
            var obj = listObject[keyObj];
            for (var keyRoom in obj.list)
            {
                var room = obj.list[keyRoom];
                for (var keyChannel in room.list)
                {
                    var channel = room.list[keyChannel];
                    if (this.checkSelectedChannel(channel))
                    {
                        room._check = true;
                        obj._check = true;
                        break;
                    }
                }
            }
        }
    }
    $scope.validLevel_3 = function(key,channel)
    {
        var nameL3 = channel.name;
        var hashL3 = md5(nameL3+channel.num_channel+channel.devEui);
        if (hashL3==key)
        {
            var filter = storage.map_nav.filterDevices;
            var fullFilter = storage.map_nav.filter;
            var checkFullFilter = storage.map_nav.checkFilter();
            if (filter||checkFullFilter)
            {
                var validDeviceModel = channel._self.device_type == fullFilter.deviceModel || fullFilter.deviceModel == undefined || fullFilter.deviceModel == 0;
                filter = filter.toLowerCase();
                if(validDeviceModel)
                {
                    var name_level_1 = channel.name_level_1;
                    if (name_level_1&&name_level_1.toLowerCase().indexOf(filter)>-1) return true;
                    var address_level_1 = channel.address_level_1;
                    if (address_level_1&&address_level_1.toLowerCase().indexOf(filter)>-1) return true;
                    var level_2 = channel.level_2;
                    if (level_2&&level_2.toLowerCase().indexOf(filter)>-1) return true;
                    var name = channel.name;
                    if (name&&name.toLowerCase().indexOf(filter)>-1) return true;
                    var devEui = channel.devEui;
                    if (devEui&&devEui.toLowerCase().indexOf(filter)>-1) return true;
                }
                return false;
            }
            return true;
        }
        return false;
    }
    $scope.$watch('check_page', function(newValue, oldValue) {
            var scope = angular.element('body').scope();
            if (scope.type_active_page)
            {
                history.pushState({page:newValue},'1');
            } 
        });
    $scope.$watch('pageDeviceEditor', function(newValue, oldValue) {
        var scope = angular.element('body').scope();
        if (scope.infoDeviceEditor)
        {
            $('#infoDeviceEditor').popover('hide');
            scope.infoDeviceEditor = false;
        }
    });
    $scope.toggleInfoDeviceEditor = function ()
    {
        $scope.infoDeviceEditor = !this.infoDeviceEditor;
        if (this.infoDeviceEditor)
        {
            $('#infoDeviceEditor').popover('show');
        }
        else
        {
            $('#infoDeviceEditor').popover('hide');
        }
    }
    $scope.getDangerReason = function (idTypeDevice,danger)
    {
        var result = '';
        if( isObject(danger) )
        {
            var tp11 = idTypeDevice == 9 && danger.version == 0;
            var tp11rev2 = idTypeDevice == 9 && danger.version == 1;
            var si_danger = idTypeDevice == 6;
            if ( tp11 )
            {
                result += danger.sensor_danger_1?danger.security_name:'';
                result += danger.sensor_danger_1&&danger.sensor_danger_2?', ':'';
                result += danger.sensor_danger_2?danger.security_name_2:'';
                result += danger.dangerEvent&&danger.dangerData?', ':'';
                result += danger.dangerData?'Отклонение от нормальных показаний!':'';
            }
            else if( tp11rev2 )
            {
                var temp = {
                    security_name: danger.security_name,
                    security_name_2: danger.security_name_2,
                }
                result += this.parseReason( danger.reason, 5, temp );
            }
            else if(si_danger)
            {
                if(danger.reason == 5)
                {
                    return "Отклонение температуры";
                }
                return "Тревога";
            }
        }
        return result;
    }
    $scope.selectPage = function(page)
    {
        this.check_page = page;
        this.type_active_page = 1;
        if (page==8)
        {
            $scope.managerReport.reload();
        }
    }
    $scope.cssSelectedSensorTp = function ( value, limit_exceeded )
    {
        var channel = $scope.storage.devices.select_channel_temp;
        if ( channel && isObject(channel._self) )
        {
            var lastValue = channel.statistics.last_sensorTP;
            var lastLimitExceeded = channel.statistics.last_limit_exceeded;
            
            var validValue = value!==undefined&&typeof value === 'number';
            var validLastValue = lastValue!==undefined&&typeof lastValue === 'number';
            
            var validLimitExceeded = value!==undefined;
            var validLastLimitExceeded = lastLimitExceeded!==undefined;
            
            if (!validValue&&validLastValue)
            {
                value = lastValue;
                validValue = true;
            }
            
            if (!validLimitExceeded&&validLastLimitExceeded)
            {
                limit_exceeded = lastLimitExceeded;
                validLimitExceeded = true;
            }
            
            if ( channel._self.version == 1 && validValue && validLimitExceeded )
            {
                var resVal = $scope.get_value4_20mA(value);
                if ( resVal!=='Неизвестно' && limit_exceeded )
                {
                    return 'danger';
                }
            }
            else if ( channel._self.version == 0 )
            {
                var min = parseFloat(channel.min_normal_v);
                var max = parseFloat(channel.max_normal_v);
                if (validValue&&!isNaN(min)&&!isNaN(max))
                {
                    var resVal = $scope.get_value4_20mA(value);
                    if (resVal!=='Неизвестно')
                    {
                        if (resVal<=min||resVal>=max)
                        {
                            return 'danger';
                        }
                    }
                }
            }
        }
        return '';
    }
    $scope.sendAllGetDataReq = function ()
    {
        var myDevices = this.storage.devices.devices_list;
        for (var i = 0; i<myDevices.length;i++)
        {
            var devEui = myDevices[i].devEui;
            if (devEui)
            {
                this.WS.send_get_device_data_req(devEui,undefined,undefined,1);
            }
        }
    }
    $scope.getNamePackage = function (dt,pt,history)
    {
        // if(history.fcnt==260)
        // {
        //     console.log('В момент когда начинаем разбераться как вывесор а экран',history.reason);
        // }
       
        var result = '-';
        try 
        {
            var dt = parseInt(dt);
            var currentVersionParserP = parseInt(history.version);
            pt = parseInt(pt);
            switch (dt) 
            {
                case 1:
                    if( currentVersionParserP >= 2)
                    {
                        if ( pt >= 0 && pt <= 4 && history.port == 2 )
                        {
                            var reason = this.parseReason(history.reason,'si11rev2');
                            result = reason;
                        }
                        else if (history.port == 195)
                        {
                            result = 'Информационный пакет';
                        }
                        else if (history.port == 85)
                        {
                            result = 'Диагностический пакет';
                        }
                        else if (pt==255 && history.port == 4 )
                        {
                            result = 'Коррекция времени';
                        }
                        else if (pt==0 && history.port == 3)
                        {
                            result = 'Настройки по воздуху';
                        }
                    }
                    else
                    {
                        if (pt==1)
                        {
                            result = 'Текущие показания';
                        }
                        else if (pt==2)
                        {
                            result = 'Тревога на канале №'+history.num_channel;
                        }
                    }
                    break;
                case 11:
                    if( currentVersionParserP >= 2)
                    {
                        if ( pt >= 0 && pt <= 5 && history.port == 2 )
                        {
                            var reason = this.parseReason(history.reason,'si21_22rev3');
                          // result = `Текущие показания (${reason})`;
                            result = reason;
                        }
                        else if (history.port == 195)
                        {
                            result = 'Информационный пакет';
                        }
                        else if (history.port == 85)
                        {
                            result = 'Диагностический пакет';
                        }
                        else if (pt==255 && history.port == 4 )
                        {
                            result = 'Коррекция времени';
                        }
                        else if (pt==0 && history.port == 3)
                        {
                            result = 'Настройки по воздуху';
                        }
                    }
                    else
                    {
                        if (pt==1)
                        {
                            result = 'Текущие показания';
                        }
                        else if (pt==2)
                        {
                            result = 'Тревога на канале №'+history.num_channel;
                        }
                    }
                    break;
                case 12:
                    if (pt==1)
                    {
                        result = 'Событие';
                    }
                    else if (pt==2)
                    {
                        result = 'Мгновенное сообщение';
                    }
                    else if (pt==3)
                    {
                        result = 'Прозрачный режим';
                    }
                    else if (pt==4)
                    {
                        result = 'Накопленная энергия';
                    }
                    else if (pt==5)
                    {
                        result = 'Профиль мощности';
                    }
                    else if (pt==6)
                    {
                        result = 'Квитанция';
                    }
                    break;
                case 3:
                    if( history.port == 4 && pt == 255 )
                    {
                        result = 'Пакет коррекции времени';
                    }
                    else if( history.port == 3 && pt == 0 )
                    {
                        result = 'Пакет настроек по воздуху';
                    }
                    else if( history.version == 0 && history.port == 2 )
                    {
                        if (pt==1)
                        {
                            result = 'Пакет с текущими показаниями';
                        }
                        else if (pt==2)
                        {
                            result = 'Пакет типа тревога';
                        }
                        else if (pt==3)
                        {
                            result = 'RS-232 или RS-485';
                        }
                        else if (pt==4)
                        {
                            result = 'Текущие показания Меркурий 206';
                        }
                        else if (pt==5)
                        {
                            result = 'Подтверждение команды ';
                        }
                    }
                    else if( history.version == 1 && history.port == 2 )
                    {
                        if (pt==1)
                        {
                            result = 'Пакет с текущими показаниями';
                        }
                        else if (pt==2)
                        {
                            result = 'Пакет типа тревога';
                        }
                        else if (pt==3)
                        {
                            result = 'RS-232 или RS-485';
                        }
                        else if (pt==4)
                        {
                            result = 'Текущие показания Меркурий 206';
                        }
                        else if (pt==5)
                        {
                            result = 'Подтверждение команды ';
                        }
                        else if (pt==6)
                        {
                            result = 'Пакет типа 6 ';
                        }
                    }
                    break;
                case 18:
                    if( currentVersionParserP >= 2)
                    {
                        if ( pt >= 0 && pt <= 5 && history.port == 2 )
                        {
                            var reason = this.parseReason(history.reason,'si21_22rev3');
                            result = reason;
                            //result = `Текущие показания (${reason})`;
                        }
                        else if (history.port == 195)
                        {
                            result = 'Информационный пакет';
                        }
                        else if (history.port == 85)
                        {
                            result = 'Диагностический пакет';
                        }
                        else if (pt==255 && history.port == 4 )
                        {
                            result = 'Коррекция времени';
                        }
                        else if (pt==0 && history.port == 3)
                        {
                            result = 'Настройки по воздуху';
                        }
                    }
                    else
                    {
                        if (pt==1)
                        {
                            result = 'Текущие показания';
                        }
                        else if (pt==2)
                        {
                            result = 'Тревога на канале №'+history.num_channel;
                        }
                        else if (history.port == 195)
                        {
                            result = 'Информационный пакет';
                        }
                        else if (history.port == 85)
                        {
                            result = 'Диагностический пакет';
                        }
                        else if (pt==255 && history.port == 4 )
                        {
                            result = 'Коррекция времени';
                        }
                        else if (pt==0 && history.port == 3)
                        {
                            result = 'Настройки по воздуху';
                        }
                    }
                    break;
                case 2:
                    if( currentVersionParserP >= 2)
                    {
                        if ( history.port == 2)
                        {
                            if ( history.reason == 0x00 ) result = 'Текущие показания, по времени';
                            else if ( history.reason == 0x01 ) result = 'Текущие показания,  cработал охранный вход 1';
                            else if ( history.reason == 0x02 ) result = 'Текущие показания,  cработал охранный вход 2';
                            else if ( history.reason == 0x03 ) result = 'Текущие показания,  cработал охранный вход 3';
                            else if ( history.reason == 0x04 ) result = 'Текущие показания,  cработал охранный вход 4';
                            else if ( history.reason == 0x05 ) result = 'Текущие показания,  превышен порог на входе 1';
                            else if ( history.reason == 0x06 ) result = 'Текущие показания,  превышен порог на входе 2';
                            else if ( history.reason == 0x07 ) result = 'Текущие показания,  превышен порог на входе 3';
                            else if ( history.reason == 0x08 ) result = 'Текущие показания,  превышен порог на входе 4';
                            else if ( history.reason == 0x09 ) result = 'Текущие показания,  По запросу';
                        }
                        else if ( history.port == 5)
                        {
                            if ( history.reason == 0x00 ) result = 'Изменилось состояние выходов';
                            else if ( history.reason == 0x01 ) result = 'Изменилось состояние внешнего питания';                              

                        }
                        else if (history.port == 195)
                        {
                            result = 'Информационный пакет';
                        }
                        else if (history.port == 85)
                        {
                            result = 'Диагностический пакет';
                        }
                        else if (pt==255 && history.port == 4 )
                        {
                            result = 'Коррекция времени';
                        }
                        else if (pt==0 && history.port == 3)
                        {
                            result = 'Настройки по воздуху';
                        }
                    }
                    else
                    {
                        if (pt==1)
                        {
                            result = 'Текущие показания';
                        }
                        else if (pt==2)
                        {
                            result = 'Тревога на канале №'+history.num_channel;
                        }
                        else if (pt==4)
                        {
                            if(history.state_energy)
                            {
                                result = 'Внешнее питание подключено';
                            }
                            else
                            {
                                result = 'Внешнее питание отключено';
                            }
                        }
                        else if (pt==5)
                        {
                        if ( typeof history.sensor_out_1 == 'boolean' )
                        {
                            if(history.sensor_out_1)
                            {
                                result = 'Выход 1 замкнут';
                            }
                            else
                            {
                                result = 'Выход 1 разомкнут';
                            }
                            
                        }
                        else if ( typeof history.sensor_out_2 == 'boolean' )
                        {
                            if(history.sensor_out_2)
                            {
                                result = 'Выход 2 замкнут';
                            }
                            else
                            {
                                result = 'Выход 2 разомкнут';
                            }
                        }
                        else
                        {
                            result = 'Изменилось состояние выхода';
                        }
                    }
                    else if (pt==255)
                    {
                        result = 'Коррекция времени';
                    }
                    }
                    break;
                case 20:
                        if (pt==1)
                        {
                            result = 'Текущие показаниями теплосчетчика';
                        }
                        else if (pt==3)
                        {
                            result = 'Данные с M_BUS';
                        }
                        else if (pt==4)
                        {
                            if(history.state_energy)
                            {
                                result = 'Внешнее питание подключено';
                            }
                            else
                            {
                                result = 'Внешнее питание отключено';
                            } 
                        }
                        else if (pt==5)
                        {
                            result = 'Тревога на канале №'+history.num_channel;
                        }
                        else if (pt==6)
                        {
                            if ( typeof history.sensor_out_1 == 'boolean' && history.num_out_channel == 1)
                            {
                                if(history.sensor_out_1)
                                {
                                    result = 'Выход 1 замкнут';
                                }
                                else
                                {
                                    result = 'Выход 1 разомкнут';
                                }
                                
                            }
                            else if ( typeof history.sensor_out_2 == 'boolean' && history.num_out_channel == 2)
                            {
                                if(history.sensor_out_2)
                                {
                                    result = 'Выход 2 замкнут';
                                }
                                else
                                {
                                    result = 'Выход 2 разомкнут';
                                }
                            }
                            else
                            {
                                result = 'Изменилось состояние выхода';
                            }
                        }
                        else if (pt==255)
                        {
                            result = 'Коррекция времени';
                        }
                        break;
                    case 21:
                        if (pt==1)
                        {
                            result = 'Текущие показаниями теплосчетчика';
                        }
                        break;
                    case 24:
                        if (pt==1)
                        {
                            result = 'Общее состояние счётчика';
                        }
                        else if (pt==2)
                        {
                            result = 'Мгновенное сообщение №1';
                        }
                        else if (pt==3)
                        {
                            result = 'Прозрачный режим';
                        }
                        else if (pt==4)
                        {
                            result = 'Накопленная энергия';
                        }
                        else if (pt==5)
                        {
                            result = 'Профиль мощности';
                        }
                        else if (pt==6)
                        {
                            result = 'Квитанция';
                        }
                        else if (pt==7)
                        {
                            result = 'Конфигурация';
                        }
                        else if (pt==8)
                        {
                            result = 'Тарифное расписание';
                        }
                        else if (pt==9)
                        {
                            result = 'Информация о счётчике №1';
                        }
                        else if (pt==10)
                        {
                            result = 'Информация о счётчике №2';
                        }
                        else if (pt==11)
                        {
                            result = 'Режим журнала превышения мощности';
                        }
                        else if (pt==12)
                        {
                            result = 'Режим реле';
                        }
                        else if (pt==13)
                        {
                            result = 'Режим индикации №1';
                        }
                        else if (pt==14)
                        {
                            result = 'Режим индикации №2';
                        }
                        else if (pt==15)
                        {
                            result = 'Список специальных дней №1';
                        }
                        else if (pt==16)
                        {
                            result = 'Архив накоплений энергии (36м)';
                        }
                        else if (pt==17)
                        {
                            result = 'Архив накоплений энергии (128с)';
                        }
                        else if (pt==18)
                        {
                            result = 'Срез активной мощности';
                        }
                        else if (pt==19)
                        {
                            result = 'Журнал питания';
                        }
                        else if (pt==20)
                        {
                            result = 'Журнал отклонения частоты';
                        }
                        else if (pt==21)
                        {
                            result = 'Журнал отклонения напряжения';
                        }
                        else if (pt==22)
                        {
                            result = 'Журнал перенапряжения';
                        }
                        else if (pt==23)
                        {
                            result = 'Журнал провалов';
                        }
                        else if (pt==24)
                        {
                            result = 'Журнал реле';
                        }
                        else if (pt==25)
                        {
                            result = 'Журнал вскрытия корпуса';
                        }
                        else if (pt==26)
                        {
                            result = 'Журнал изменения времени';
                        }
                        else if (pt==27)
                        {
                            result = 'Журнал коррекции времени';
                        }
                        else if (pt==28)
                        {
                            result = 'Журнал изменения тарифного расписания';
                        }
                        else if (pt==29)
                        {
                            result = 'Журнал команд записи по интерфейсу';
                        }
                        else if (pt==30)
                        {
                            result = 'Журнал превышения мощности';
                        }
                        else if (pt==31)
                        {
                            result = 'Журнал пиковых напряжений';
                        }
                        else if (pt==32)
                        {
                            result = 'Мгновенное сообщение №2';
                        }
                        else if (pt==33) 
                        {
                            result = 'Список специальных дней №2';
                        }
                        else if (pt==255)
                        {
                            result = 'Коррекция времени';
                        }
                        else if (pt==0 && history.port == 3)
                        {
                            result = 'Настройки по воздуху';
                        }
                        break;
                    case 27:
                        if (pt==1)
                        {
                            result = 'Событие';
                        }
                        else if (pt==2)
                        {
                            result = 'Мгновенное сообщение';
                        }
                        else if (pt==3)
                        {
                            result = 'Прозрачный режим';
                        }
                        else if (pt==4)
                        {
                            result = 'Накопленная энергия';
                        }
                        else if (pt==5)
                        {
                            result = 'Профиль мощности';
                        }
                        else if (pt==6)
                        {
                            result = 'Квитанция';
                        }
                        break;
                    case 28:
                        if (currentVersionParserP >= 2) {
                            if (pt == 0x0B){
                                result = '1-Wire';
                            }else if (pt == 4){
                                result = 'ModBus';
                            }else if (pt == 0x0A){
                                result = 'Текущие показания';
                            }else if (pt == 0x0D){
                                result = 'Прозрачный режим'
                            }else if (pt == 5){
                                result = 'Прозрачный режим с меткой времени'
                            }else if (pt == 6){
                                result = 'ModBus с меткой времени'
                            }else if (pt == 0xAA){
                                result = 'Отсутствие ответа по ModBus'
                            }else if (pt == 0x0C){
                                result = 'Восстановление обмена ModBus'
                            }else if (pt == 0xC3){
                                result = 'Информационный пакет';
                            }
                            break;
                        } else {
                            if (pt == 1) {
                                result = '1-Wire';
                            }
                            else if (pt == 9) {
                                result = 'ModBus';
                            }
                            break;
                        }
                    case 30:
                        if (pt==1)
                        {
                            result = 'Текущие показаниями теплосчетчика';
                        }
                        else if (pt==255)
                        {
                            result = 'Коррекция времени';
                        }
                        break;
                    case 31:
                        if( history.port == 2 )
                        {
                            if ( pt === 5 )
                            {
                                result = 'Пожар';
                            }
                            else if ( pt === 6 )
                            {
                                result = 'Тест';
                            }
                            else if ( pt === 7 )
                            {
                                result = 'Тревога по солидарной линии работы';
                            }
                            else if ( pt === 8 )
                            {
                                result = 'Снятие';
                            }
                            else if ( pt === 9 )
                            {
                                result = 'Сброс тревоги';
                            }
                            else if ( pt === 10 )
                            {
                                result = 'Низкий заряд АКБ';
                            }
                            else if ( pt === 11 )
                            {
                                result = 'Постановка на охрану';
                            }
                            else if ( pt === 12 )
                            {
                                result = 'Стоп охраны';
                            }
                            else if ( pt === 13 )
                            {
                                result = 'Отключение охраны';
                            }
                            else if ( pt === 14 )
                            {
                                result = 'Ошибка датчика';
                            }
                            else if ( pt === 15 )
                            {
                                result = 'Запыленность камеры датчика';
                            }
                            else if ( pt === 16 )
                            {   
                                result = 'По времени';
                            }
                        }
                        else if (history.port == 195)
                        {
                            result = 'Информационный пакет';
                        }
                        else if (history.port == 85)
                        {
                            result = 'Диагностический пакет';
                        }
                        else if (pt==255 && history.port == 4 )
                        {
                            result = 'Коррекция времени';
                        }
                        else if (pt==0 && history.port == 3)
                        {
                            result = 'Настройки по воздуху';
                        }
                        break;
                default:
                        if (pt==255)
                        {
                            result = 'Коррекция времени';
                        }
                    break;
            }
        }
        catch(e)
        {
            
        }
        finally 
        {
            return result;
        }
    }
    $scope.getActiveDevice = function ()
    {
        var channel = this.storage.devices.select_channel_temp;
        if (channel)
        {
            var devEui = this.storage.devices.select_channel_temp.devEui;
            var dev = this.storage.devices.get_device(devEui);
            if (dev) return dev;
        }
        return new Object();
    }
    $scope.getText_ReasonUE = function(value,dt){
        if(dt == 24)
        {
            switch (value) {
                case 1:
                        return "По времени";
                    break;
                case 2:
                        return "Вскрытие клеммной крышки";
                    break;
                case 3:
                        return "Вскрытие корпуса";
                    break;
                case 4:
                        return "Магнитное воздействие";
                    break;
                case 5:
                        return "Потеря фазы";
                    break;
                case 6:
                        return "Инверсия фазы";
                    break;
                case 7:
                        return "Срабатывание реле";
                    break;
                case 8:
                        return "Превышение напряжения по фазе A";
                    break;
                case 9:
                        return "Превышение напряжения по фазе B";
                    break;
                case 10:
                        return "Превышение напряжения по фазе C";
                    break;
                case 11:
                        return "Превышение лимита мощности";
                    break;
                case 12:
                        return "Превышение лимита активной мощности";
                    break;
                case 13:
                        return "Превышение лимита энергии по тарифу 1";
                    break;
                case 14:
                        return "Превышение лимита энергии по тарифу 2";
                    break;
                case 15:
                        return "Превышение лимита энергии по тарифу 3";
                    break;
                case 16:
                        return "Превышение лимита энергии по тарифу 4";
                    break;
                case 17:
                        return "Разряд встроенной батареи";
                    break;
                case 18:
                        return "Отключение подачи электроэнергии";
                    break;    
                case 19:
                        return "По запросу";
                    break; 
                case 20:
                        return "Включение электропитания счетчика";
                    break;
                case 21:
                        return "Провал напряжения по фазе А";
                    break;
                case 22:
                        return "Провал напряжения по фазе В";
                    break;
                case 23:
                        return "Провал напряжения по фазе С";
                    break;
                case 24:
                        return "Отклонение частоты";
                    break;
                default:
                    return 'Неизвестно';
                    break;
            }
        }
        else if(dt == 27)
        {
            switch (value) {
                case 1:
                        return "По времени";
                    break;
                case 2:
                        return "Вскрытие клеммной крышки";
                    break;
                case 3:
                        return "Вскрытие корпуса";
                    break;
                case 4:
                        return "Магнитное воздействие";
                    break;
                case 5:
                        return "Потеря фазы";
                    break;
                case 6:
                        return "Инверсия фазы";
                    break;
                case 7:
                        return "Срабатывание реле";
                    break;
                case 8:
                        return "Превышение напряжения по фазе 1";
                    break;
                case 9:
                        return "Превышение напряжения по фазе 2";
                    break;
                case 10:
                        return "Превышение напряжения по фазе 3";
                    break;
                case 11:
                        return "Превышение лимита мощности";
                    break;
                case 12:
                        return "Превышение лимита активной мощности";
                    break;
                case 13:
                        return "Превышение лимита энергии по тарифу 1";
                    break;
                case 14:
                        return "Превышение лимита энергии по тарифу 2";
                    break;
                case 15:
                        return "Превышение лимита энергии по тарифу 3";
                    break;
                case 16:
                        return "Превышение лимита энергии по тарифу 4";
                    break;
                case 17:
                        return "Разряд встроенной батареи";
                    break;
                case 18:
                        return "Отключение подачи электроэнергии";
                    break;    
                case 19:
                        return "По запросу";
                    break; 
                case 20:
                        return "Включение электропитания счетчика";
                    break;
                case 21:
                        return "Закрытие клеммной крышки";
                    break;
                case 22:
                        return "Закрытие корпуса";
                    break;
                default:
                    return 'Неизвестно';
                    break;
            }
        }
        else
        {
            switch (value) {
                case 1:
                        return "По времени";
                    break;
                case 2:
                        return "Вскрытие клеммной крышки";
                    break;
                case 3:
                        return "Вскрытие корпуса";
                    break;
                case 4:
                        return "Магнитное воздействие";
                    break;
                case 5:
                        return "Потеря фазы";
                    break;
                case 6:
                        return "Инверсия фазы";
                    break;
                case 7:
                        return "Срабатывание реле";
                    break;
                case 8:
                        return "Превышение напряжения по фазе 1";
                    break;
                case 9:
                        return "Превышение напряжения по фазе 2";
                    break;
                case 10:
                        return "Превышение напряжения по фазе 3";
                    break;
                case 11:
                        return "Превышение лимита мощности";
                    break;
                case 12:
                        return "Превышение лимита активной мощности";
                    break;
                case 13:
                        return "Превышение лимита энергии по тарифу 1";
                    break;
                case 14:
                        return "Превышение лимита энергии по тарифу 2";
                    break;
                case 15:
                        return "Превышение лимита энергии по тарифу 3";
                    break;
                case 16:
                        return "Превышение лимита энергии по тарифу 4";
                    break;
                case 17:
                        return "Разряд встроенной батареи";
                    break;
                case 18:
                        return "Отключение подачи электроэнергии";
                    break;    
                case 19:
                        return "По запросу";
                    break; 
                case 20:
                        return "Включение электропитания счетчика";
                    break;
                default:
                    return 'Неизвестно';
                    break;
            }
        }
    }
   
    $scope.parseEventUE = function (value,dt)
    {
        if(!dt) dt = 12;
        var channel = $scope.storage.devices.select_channel_temp;
        var lastEvent = channel&&channel.statistics&&channel.statistics.last_event?channel.statistics.last_event:undefined;
        if (value===undefined&&lastEvent!==undefined)
        {
            value=lastEvent;
        }
        if (channel&&value!==undefined&&channel.type_channel==14)
        {
            value = parseInt(value);
            if (!isNaN(value))
            {
                return this.getText_ReasonUE(value,dt);
            }
        }
        return 'Неизвестно';
    }
    $scope.getText_ReasonSmart=function(type,value,channel)
    {
        switch (type) {
            case 10:
                if (value===0)
                {
                    return 'По времени';
                } 
                else if (value===1)
                {
                    return 'Сработал магнитый датчик';
                }
                else if (value===2)
                {
                    return 'Сработал магнитый датчик 2';
                }
                break;
            case 11:
                if (value===0)
                {
                    return 'По времени';
                } 
                else if (value===1)
                {
                    return 'Сработал датчик движения';
                }
                break;
            case 12:
                if (value===0)
                {
                    return 'По времени';
                } 
                else if (value===1)
                {
                    return 'Сработал по тревоге';
                }
                else if (value===2)
                {
                    return 'По автопостановке на охрану';
                }
                break;
            case 13:
                if (value===0)
                {
                    return 'По времени';
                } 
                else if (value===1)
                {
                    return 'Задымление';
                }
                else if (value===2)
                {
                    return 'Сработал магнитый датчик';
                }
                break;
            case 23:
                if (value===1)
                {
                    return 'По времени';
                } 
                else if (value===2)
                {
                    if(channel.security_name) return channel.security_name;
                    return 'По датчику открытия 1';
                }
                else if (value===3)
                {
                    if(channel.security_name_2) return channel.security_name_2;
                    return 'По датчику открытия 2';
                }
                else if (value===4)
                {
                    return 'По акселерометру';
                }
                else if (value===5)
                {
                    return 'По выходу влажности за установленные пороги';
                }
                else if (value===6)
                {
                    return 'По выходу температуры за установленные пороги';
                }
                break;
            case 25:
                if (value===1)
                {
                    return 'По времени';
                } 
                else if (value===2)
                {
                    return 'По выходу СО2 за установленные пороги';
                }
                else if (value===3)
                {
                    // if(channel.security_name_2) return channel.security_name;
                    return 'По выходу уровня освещенности за установленные пороги';
                }
                else if (value===4)
                {
                    return 'По акселерометру';
                }
                else if (value===5)
                {
                    return 'По выходу влажности за установленные пороги';
                }
                else if (value===6)
                {
                    return 'По выходу температуры за установленные пороги';
                }
                else if (value===7)
                {
                    return 'По выходу уровня шума за определенные пороги';
                }
                else if (value===8)
                {
                    return 'Обнаружение снятия';
                }
                break;
            case 31:
                if ( value === 5 )
                {
                    return 'Пожар';
                }
                else if ( value === 6 )
                {
                    return 'Тест';
                }
                else if ( value === 7 )
                {
                    return 'Тревога по солидарной линии работы';
                }
                else if ( value === 8 )
                {
                    return 'Снятие';
                }
                else if ( value === 9 )
                {
                    return 'Сброс тревоги';
                }
                else if ( value === 10 )
                {
                    return 'Низкий заряд АКБ';
                }
                else if ( value === 11 )
                {
                    return 'Постановка на охрану';
                }
                else if ( value === 12 )
                {
                    return 'Стоп охраны';
                }
                else if ( value === 13 )
                {
                    return 'Отключение охраны';
                }
                else if ( value === 14 )
                {
                    return 'Ошибка датчика';
                }
                else if ( value === 15 )
                {
                    return 'Запыленность камеры датчика';
                }
                else if ( value === 16 )
                {   
                    return 'По времени';
                }
                break;
            default:
                return 'Неизвестно';
                break;
        }
    }
    $scope.getTextNamePowerProfile = function(typeMeter,type)
    {
        var namePowerProfile = 'мощности';
        if(type==2) namePowerProfile = 'Мощность';
        if( typeMeter && typeMeter == 5 )
        {
            namePowerProfile = 'энергии';
            if(type==2) namePowerProfile = 'Энергия';
        }
        return namePowerProfile;
    }
    $scope.getVersionSelectedChannelNumber = function()
    {
        var version = this.getVersionSelectedChannel();
        if( version === undefined ) return -1;
        version = parseInt(version);
        if(isNaN(version)) return -1;
        return version;
    }
    $scope.getVersionSelectedChannel = function ()
    {
        var selectedChannel = $scope.storage.devices.select_channel_temp;
        var validSelectedChannel = isObject(selectedChannel) && isObject(selectedChannel._self) ;
        if( validSelectedChannel )
        {
            var selectedDevice = selectedChannel._self;
            var version = selectedDevice.version;
            if( version !== undefined )
            {
                return version.toString();
            }
            else
            {
                var deviceType = storage.type_device_list.get_type_device(selectedDevice.device_type); 
                deviceType = storage.type_device_list.get_type_device(deviceType);
                if( isObject(deviceType) )
                {
                    return storage.type_device_list.get_key_first_settings_type_device(selectedDevice.device_type).toString();
                }
            }
        }
        return undefined;
    }
    $scope.yesOrNo = function (val)
    {
        var yes = val === true || val === 1 || val === '1';
        var no = val === false || val === 0 || val === '0';
        if(yes) return 'Да';
        if(no) return 'Нет';
        return '-';
    }
    $scope.parseReasonSmart = function (value)
    {
        var channel = $scope.storage.devices.select_channel_temp;
        var lastReason = channel.statistics.last_reason;
        if (value===undefined&&lastReason!==undefined)
        {
            value=lastReason;
        }
        if (channel&&value!==undefined)
        {
            value = parseInt(value)
            var id_type_channel = parseInt(channel.type_channel);
            return this.getText_ReasonSmart(id_type_channel,value,channel);
        }
        return 'Неизвестно';
    }
    $scope.get_value0_21mB = function (value)
    {
        var channel = $scope.storage.devices.select_channel_temp;
        if (channel)
        {
            var lastValue;
            if (channel!==undefined&&channel.statistics!=undefined)
            {
                lastValue = channel.statistics.last_sensor;
            }
            var validValue = value!==undefined&&typeof value === 'number';
            var validLastValue = lastValue!==undefined&&typeof lastValue === 'number';
            if (!validValue&&validLastValue)
            {
                value = lastValue;
                validValue = true;
            }
            var min_v = parseFloat(channel.min_v);
            var max_v = parseFloat(channel.max_v);
            
            if (validValue&&!isNaN(min_v)&&!isNaN(max_v))
            {
                if (value>=21000||value<=0)
                {
                    return 'Неизвестно';
                }
                var newvalue = $scope.my_converter.parse0_21mB(value,min_v,max_v);
                if (typeof newvalue === 'number')
                {
                    return $scope.my_converter.round_size(newvalue,4);
                }
            }
        }
        return 'Неизвестно';
    }
    $scope.get_value4_20mA = function (value)
    {
        var channel = $scope.storage.devices.select_channel_temp;
        if (channel)
        {
            var lastValue;
            if (channel!==undefined&&channel.statistics!=undefined)
            {
                lastValue = channel.statistics.last_sensorTP;
            }
            var validValue = value!==undefined&&typeof value === 'number';
            var validLastValue = lastValue!==undefined&&typeof lastValue === 'number';
            if (!validValue&&validLastValue)
            {
                value = lastValue;
                validValue = true;
            }
            var min_v = parseFloat(channel.min_v);
            var max_v = parseFloat(channel.max_v);
            
            if (validValue&&!isNaN(min_v)&&!isNaN(max_v))
            {
                if (value===0)
                {
                    return 'Неизвестно';
                }
                else if (value<=25&&value>=2)
                {
                    var newvalue = $scope.my_converter.parse4_20mA(value,min_v,max_v);
                    if (typeof newvalue === 'number')
                    {
                        return $scope.my_converter.round_size(newvalue,4);
                    }
                }
                else
                {
                    return 'Неизвестно';
                }
            }
        }
        return 'Неизвестно';
    }
    $scope.slider_change = function ()
    {
         $scope.editDevice.min_t=$scope.slider.minValue; 
         $scope.editDevice.max_t=$scope.slider.maxValue;
    }
    $scope.slider_val_change = function ()
    {
        $scope.editDevice.min_normal_v=$scope.slider_val.minValue; 
        $scope.editDevice.max_normal_v=$scope.slider_val.maxValue;
    }
    
    $scope.refreshSlider = function () {
        if ($scope.editDevice!==undefined&&$scope.editDevice.min_t!=undefined)
        {
            $scope.slider.minValue = $scope.editDevice.min_t;
        }
        else
        {
            $scope.slider.minValue = -55;
        }
        if ($scope.editDevice!==undefined&&$scope.editDevice.max_t!=undefined)
        {
            $scope.slider.maxValue = $scope.editDevice.max_t;
        }
        else
        {
            $scope.slider.maxValue = 100;
        }
        $timeout(function () {
          $scope.$broadcast('rzSliderForceRender')
        })
    }
    $scope.refreshSlider_val = function () {
        $timeout(function () {
          $scope.$broadcast('rzSliderForceRender')
        })
    }
    $scope.slider = {
        minValue: -55,
        maxValue: 100,
        options: {
            floor: -55,
            step: 1,
            ceil:100,
            noSwitching: true,
            autoHideLimitLabels:true,
            onChange:$scope.slider_change
        }
    };
    $scope.slider_out = {
        minValue: 0,
        options: {
            floor: 0,
            step: 1,
            ceil:255,
            hideLimitLabels:true,
            translate: function(value) {
            	if (value===0)
              {
              	return 'Навсегда'
              }
              return value+' с';
            }
        }
    };
    $scope.time_sensors_out_ug = 0;
    $scope.slider_out_ug = {
        minValue: 0,
        options: {
            floor: 0,
            step: 5,
            ceil:65535,
            hideLimitLabels:true,
            translate: function(value) {
            	if (value===0)
              {
              	return 'Навсегда'
              }
              return value+' с';
            }
        }
    };
    $scope.slider_val = {
        minValue: 0,
        maxValue: 100,
        options: {
            floor: 0,
            step: 1,
            ceil:1000,
            noSwitching: true,
            autoHideLimitLabels:true,
            onChange:$scope.slider_val_change,
            enforceStep:false,
            precision:0
        }
    };
    $scope.getCssClassesDeviceTypeForDeviceEditor = function(typeDevice)
    {
        var device = storage.edit_device_main;
        var cssClasses = '';
        var recomendationType = this.storage.type_device_list.get_type_device_on_appEui(device.appEui);
        var recomendation = recomendationType.id==typeDevice.id;
        var selected = typeDevice.id==device.selected_device_type;
        var saved = typeDevice.id==device.device_type;
        if (recomendation) cssClasses+='recomendation ';
        if (selected) cssClasses+='selected ';
        if (saved) cssClasses+='saved ';
        return {
            text:cssClasses,
            recomendation:recomendation,
            selected:selected,
            saved:saved
        };
    }
    $scope.changeTypeCargo = function ()
    {
        for (var i = 0 ; i<storage.type_cargo_list.length;i++)
        {
            var type = storage.type_cargo_list[i];
            if (type.id == $scope.editDevice.typeCargo)
            {
                $scope.editDevice.min_t = type.min_temperature;
                $scope.editDevice.max_t = type.max_temperature;
            }
        }
    }
    $scope.changeRangeValue = function ()
    {
        if ($scope.editDevice.valid_range_value())
        {
            var min = $scope.editDevice.min_v;
            var max = $scope.editDevice.max_v;
            var max_normal = $scope.editDevice.max_normal_v;
            var min_normal = $scope.editDevice.min_normal_v;
            var precision = 0;
            if (!$scope.editDevice.valid_range_normal_value())
            {
                max_normal = max;
                min_normal = min;
            }
            var count = Math.abs(max - min);
            var floor = min;
            var step = 1;
            if (min % 1 === 0&&max % 1 === 0)
            {
                if (count<10)
                {
                    step=0.1;
                    precision=1;
                }
                else
                {
                    step=1;
                }
            }
            else 
            {
                var countMin = 0;
                var countMax = 0;
                var arrMin = min.toString().split('.');
                var arrMax = max.toString().split('.');
                if (arrMin[1]&&arrMin[1].length>0)
                {
                    countMin = arrMin[1].length;
                }
                if (arrMax[1]&&arrMax[1].length>0)
                {
                    countMax = arrMax[1].length;
                }
                var countMM = countMax>countMin?countMax:countMin;
                if (countMM>0)
                {
                    step= 1/Math.pow(10,countMM);
                    precision=countMM;
                }
                else
                {
                    if (count<10)
                    {
                        step=0.1;
                        precision=1;
                    }
                    else
                    {
                        step=1;
                    }
                }
            }
            var ceil = max;
            $scope.slider_val.minValue=parseFloat(min);
            $scope.slider_val.maxValue=parseFloat(max);
            $scope.slider_val.options.floor=parseFloat(floor);
            $scope.slider_val.options.step=parseFloat(step);
            $scope.slider_val.options.ceil=parseFloat(ceil);
            $scope.slider_val.options.precision=parseFloat(precision);
            $scope.slider_val.minValue=parseFloat(min_normal);
            $scope.slider_val.maxValue=parseFloat(max_normal);
            $scope.editDevice.min_normal_v = $scope.slider_val.minValue;
            $scope.editDevice.max_normal_v = $scope.slider_val.maxValue;
        }
        $scope.refreshSlider_val();
    };
    $scope.spanBattery =function(charge){
        if (charge===false)
        {
            return false;
        }
        else
        {
            if (charge<15)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    $scope.refreshLevel_2 = function ()
    {
        if ($scope.editDevice.level_2===undefined)
        {
            $scope.editDevice.level_2='';
        }
        else if ($scope.editDevice.level_2==='')
        {
            $scope.editDevice.level_2 = undefined;
        }
    }
    $scope.refreshDevices=function ()
    {
        this.WS.send_get_device();
    }
    $scope.exit=function ()
    {
        $scope.WS.send_json(JSON.stringify({
            cmd:'close_auth_req',
            token:get_cookie('token')
        }));
    };
     $('#page2').scroll(function () {
            $scope.scrollFind();
            $scope.$apply(function (){
                $scope.scrollShow;
            });
        });
    $scope.availableChannelDevice = function(device)
    {
        for (var j = 0; j <storage.devices.devices_list.length;j++ )
        {
            if (storage.devices.devices_list[j].devEui==device.devEui)
            {
                var dev = storage.devices.devices_list[j];
                var dt = dev.device_type;
                var deviceType = storage.type_device_list.get_type_device(dt);
                if( isObject(deviceType) )
                {
                    var countChannels = deviceType.count_channels;
                    var activeChannels = storage.devices.get_active_channel(device.devEui).length;
                    if (countChannels-activeChannels>0)
                    {
                        return true;
                    }
                } 
                else
                {
                    return true;
                }
                return false;
            }
        }
        for (var j = 0; j <storage.devices.full_devices_list.length;j++ )
        {
            if (storage.devices.full_devices_list[j].devEui==device.devEui)
            {
                return true;
            }
        }
        return false;
    }
    $scope.Filter_device=function(device)
    {
        if ( isObject(device) && device.devEui )
        {
            var valid = new valid_data();
            var ok = false;
            var countSelectedGroups = 0;
            var countToggleGroups = this.storage.devices.countSelectedGroup();
            for (var i = 0; i < this.storage.devices.group_list.length; i++)
            {
                var group = this.storage.devices.group_list[i];
                var matchedGroups = group.title == device.group || (!device.group&&group.title=='Other');
                if (matchedGroups&&group.toggle)
                {
                    ok = true;
                    countSelectedGroups++;
                    break;
                }
            }
            var selectedAllGroup = countToggleGroups===0||this.storage.devices.group_list.length===countToggleGroups;
            if (!selectedAllGroup&&!ok) return false;
            if ($scope.filter_device!=undefined&&$scope.filter_device&&$scope.filter_device!='')
            {
                var devName = device.devName;
                if (devName==undefined)
                {
                    devName = '';
                }
                var group = device.group;
                if (group==undefined)
                {
                    group = '';
                }
                if ((device.devEui.toLowerCase().indexOf(this.filter_device.toLowerCase())<0&&devName.toLowerCase().indexOf(this.filter_device.toLowerCase())<0&&(group.toLowerCase().indexOf(this.filter_device.toLowerCase())<0)))
                {
                    return false;
                }
                else
                {
                     return true;
                }
            }
            else if (valid.devEui(device.devEui))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    $scope.scrollFind = function ()
    {
        if ($('#page2').scrollTop()>100)
        {
            this.scrollShow=true;
        }
        else
        {
           this.scrollShow=false;
        }
    }
    $scope.scrollShow = false;
    $scope.scrollToEl = function(el)
    {
        setTimeout(function (){
            $('#page2').animate({ scrollTop: $('#'+el).offset().top-300 }, 1100);
        },100);
    }
    $scope.scrollToElHome = function ()
    {
        $('#page2').animate({ scrollTop: 0 }, 1100);
        
    }
    $scope.convert_date=function(date,ct)
    {
        if (date&&date>1000)
        {
            if (ct==14)
            {
               return moment(date).utc().format('LLL').replace(',',''); 
            }
            if (ct==18)
            {
               return moment(date).format('DD MMMM YYYY').replace(',',''); 
            }
            // if( ct==12 || ct==24 ) date - moment().utcOffset()*60*1000;
            return moment(date).format('LLL').replace(',','');
        }
        else
        {
            if (ct==18)
            {
               return moment().startOf('day').format('DD MMMM YYYY').replace(',',''); 
            }
            return "Неизвестно";
        }
    }
    $scope.my_limit=function ()
    {
      return this.step_data*this.count_data;  
    }
    $scope.my_limit_event=function ()
    {
      return this.step_data_event*this.count_data_event;  
    }
    $scope.my_limit_energy=function ()
    {
      return this.step_data_energy*this.count_data_energy;  
    }
    $scope.my_limit_energy_archive=function ()
    {
      return this.step_data_energy_archive*this.count_data_energy_archive;  
    }
    $scope.my_limit_slices=function ()
    {
      return this.step_data_slices*this.count_data_slices;  
    }
    $scope.my_limit_journals=function ()
    {
      return this.step_data_journals*this.count_data_journals;  
    }
    $scope.my_limit_history=function ()
    {
      return this.step_data_history*this.count_data_history;  
    }
    $scope.my_limit_instant=function ()
    {
      return this.step_data_instant*this.count_data_instant;  
    }
    $scope.my_limit_instant2=function ()
    {
      return this.step_data_instant2*this.count_data_instant2;  
    }
    $scope.my_limit_info=function ()
    {
      return this.step_data_info*this.count_data_info;  
    }
    $scope.my_limit_info2=function ()
    {
      return this.step_data_info2*this.count_data_info2;  
    }
    $scope.my_limit_jp=function ()
    {
      return this.step_data_jp*this.count_data_jp;  
    }
    $scope.my_limit_rl=function ()
    {
      return this.step_data_rl*this.count_data_rl;  
    }
    $scope.storage = storage;
    $scope.type_active_page = 1; 
    $scope.setting_page = 0;
    $scope.device_page = 0;
    $scope.check_page='1';//Выбранная страницa
    $scope.newDevice = new Object();//создоваемое устройство
    $scope.editDevice = new edit_device();//редактируемое устройство
    
    $scope.$watch('device_page',function (newValue,oldValue){
        if(newValue == 0) return;
        else if(newValue == 1) $scope.showSettingsDevice();
        else if(newValue == 2) $scope.showDiagnosticDevice();
        else if(newValue == 3) $scope.showInfoDevice();
        return;
    });
    $scope.removeEditDevice = function ()
    {
        var name = this.editDevice.name;
        var num_channel = this.editDevice.num_channel;
        var devEui = this.editDevice.device.devEui;
        this.removeDevice(name,num_channel,devEui);
    }
    $scope.removeDevice=function(name,num,devEui)
    {
        this.universalConfirm('Внимание! Данное действие необратимо.',
        'Вы точно хотете удалить '+name+'?',
        ()=>{
            $scope.editDevice.device = new Object();
            $scope.editDevice.device.devEui=devEui;
            $scope.editDevice.num_channel = num;
            this.WS.deleteDevice($scope.editDevice.device.devEui,$scope.editDevice.num_channel);
        }
        );
        // if (confirm('Вы точно хотете удалить '+name+'?'))
        // {
           
        // }
        // else
        // {
            
        // }
    }
    $scope.deleteDevice=function ()
    {
        $scope.WS.deleteDevice($scope.editDevice.device.devEui,$scope.editDevice.num_channel);
    }
    $scope.home=function (){
        $scope.selectPage(1);
    }
    $scope.reload_full_charts=function (){
        if (this.storage.devices.get_select_channel()!=undefined)
        {
            var type= this.storage.type_channel_list.get_type_channel(this.storage.devices.get_select_channel().type_channel).type;
            var dev = this.storage.devices.get_select_channel()._self;
            var currentVersion = parseInt(dev.version);
            var si21_22 = dev.device_type == 11 || dev.device_type == 18;
            var si12rev2 = dev.device_type == 2 && currentVersion>=2;
            if (type==1)
            {
                this.reload_charts2();
                this.reload_charts3();
                this.reload_charts();
                this.reload_charts1();
                this.reload_charts_consum_v5();
                if( si12rev2 || (si21_22 && currentVersion >= 2) )
                {
                    if(!si12rev2)this.reload_chart_temperature_new();
                    this.reload_charts_danger_4();
                }
                else
                {
                    this.reload_charts4();
                }
           }
           else if (type==2)
           {
                this.reload_charts2();
                if( si12rev2 || ( si21_22 && currentVersion >= 2 ) )
                {
                    if(!si12rev2)this.reload_chart_temperature_new();
                    this.reload_charts_danger_4();
                }
                else
                {
                    this.reload_charts4();
                    this.reload_charts_danger();
                }
               
           }
           else if (type == 3 || type == 12)
           {
               this.reload_charts4();
               this.reload_charts_danger_4();
               this.reload_chart_temperature_new();
           }
           else if (type == 4)
           {
               this.reload_charts4();
               this.reload_charts1();
               this.reload_charts_danger_4();
               this.reload_charts_consum_v5();
           }
            else if (type == 5)
           {
               this.reload_charts4();
               this.reload_charts1();
               this.reload_charts_danger_4();
               if(dev.version == 1) this.reload_chart_sensor_new();
               
           }
            else if (type == 6)
           {
                 this.reload_charts4();
                 this.reload_charts_danger_4();
           }
           else if (type == 7)
           {
                 this.reload_charts4();
                 this.reload_charts_danger_4();
                 this.reload_charts1();
                 this.reload_chart_power_profile();
                 this.reload_charts_consum_v4();
           }
           else if (type == 8)
           {
                 this.reload_charts4();
                 this.reload_charts_danger_4();
                 this.reload_charts1();
                 this.reload_charts_consum_v5();
           }
           else if (type == 9)
           {
                 this.reload_charts1();
                 this.reload_charts_consum_v4();
           }
           else if (type == 10)
           {
                 this.reload_charts4();
                 this.reload_charts_danger_4();
           }
           else if (type == 11)
           {
                 this.reload_chart_temperature();
                 this.reload_charts_danger_4();
           }
           else if (type == 20)
           {
                this.reload_charts1();
            //    this.reload_charts4();
            //    this.reload_charts_danger_4();
               this.reload_chart_temperature_multi();
           }
           else if ( type == 23 )
           {
                this.reload_charts_danger_4();
                this.reload_chart_temperature_new();
                this.reload_chart_sensor_new(type);
               //smart hs0101
           }
           else if ( type == 25 )
           {
                this.reload_charts_danger_4();
                this.reload_chart_temperature_new();

                this.reload_chart_damp_new();
                this.reload_chart_lux_new();
                this.reload_chart_dB_new();
                this.reload_chart_CO2_new();
                // this.reload_chart_sensor_new(type);
               //smart um0101
           }
           else if (type == 26)
           {
                 this.reload_charts4();
                 this.reload_charts_danger_4();
           }
           else if (type == 28)
           {
                 this.reload_chart_temperature();
           }
           else if (type == 29)
           {
                 this.reload_chart_sensor_new(29);
                 this.reload_charts4();
           }
           else if (type == 30)
           {

           }
           
       }
    }
    $scope.reload_chart_temperature = function ()
    {
        var channel = this.storage.devices.select_channel_temp;
        var typeChannel = this.storage.type_channel_list.get_type_channel(channel.type_channel).type;
        var sh02_1wire = typeChannel==28;
        var statistics = this.storage.devices.get_select_channel().statistics;
        if(!sh02_1wire) this.highcharts_temperature(statistics.chart_t);
        else this.highcharts_temperature_1wire(statistics.chart_t,channel);
        
        this.charts_count++;
    }
    $scope.showSi21_22rev3 = function ()
    {
        try
        {
            var channel = storage.devices.select_channel_temp;
            var dev = channel._self;
            var deviceType = dev.device_type;
            var currentVersion = parseInt(this.getVersionSelectedChannelNumber());
            var idTypeChannelId = channel.type_channel;
            var typeChannel = this.storage.type_channel_list.get_type_channel(idTypeChannelId);
            
            var si21_22 = deviceType == 11 || deviceType == 18;
            var si21_22rev3 = si21_22 && currentVersion >= 2;
        }
        catch(e)
        {
            return false;
        }
        return si21_22rev3;
    }
    $scope.showDangersAll = function ()
    {
        try
        {
            var channel = storage.devices.select_channel_temp;
            var dev = channel._self;
            var deviceType = dev.device_type;
            var currentVersion = parseInt(this.getVersionSelectedChannelNumber());
            var idTypeChannelId = channel.type_channel;
            var typeChannel = this.storage.type_channel_list.get_type_channel(idTypeChannelId).type;
            var dangerChannel = typeChannel == 2;
            var mbus_device = deviceType == 20;
            var si13 = deviceType == 3;
            var si12 = deviceType == 2;
            var sh = deviceType == 28;
            var si21_22 = deviceType == 11 || deviceType == 18;
            var si21_22rev3 = si21_22 && currentVersion >= 2;
            var si12rev2 = si12 && currentVersion >= 2;
        }
        catch(e)
        {
            return false;
        }
        return dangerChannel&&!mbus_device&&!si13&&!si12&&!sh&&!si21_22rev3&&!si12rev2;
    }
    $scope.showChartDangersSi21_22rev3 = function ()
    {
        try
        {
            var channel = storage.devices.select_channel_temp;
            var dev = channel._self;
            var deviceType = dev.device_type;
            var currentVersion = parseInt(this.getVersionSelectedChannelNumber());
            var si21_22 = deviceType == 11 || deviceType == 18;
            var si21_22rev3 = si21_22 && currentVersion >= 2;
            var si12rev2 = deviceType == 2 && currentVersion >= 2;
        }
        catch(e)
        {
            return false;
        }
        return si21_22rev3||si12rev2;
    }
    $scope.showChartDangersAll = function ()
    {
        try
        {
            var channel = storage.devices.select_channel_temp;
            var dev = channel._self;
            var deviceType = dev.device_type;
            var currentVersion = parseInt(this.getVersionSelectedChannelNumber());
            var idTypeChannelId = channel.type_channel;
            var typeChannel = this.storage.type_channel_list.get_type_channel(idTypeChannelId).type;
            var dangerChannel = typeChannel == 2;
            var si12 = deviceType == 2;
            var si21_22 = deviceType == 11 || deviceType == 18;
            var si21_22rev3 = si21_22 && currentVersion >= 2;
            var si12rev2 = si12 && currentVersion >= 2;
        }
        catch(e)
        {
            return false;
        }
        return dangerChannel&&!si21_22rev3&&!si12rev2;
    }
    $scope.showChartsTemperature = function()
    {
        try
        {
            var channel = storage.devices.select_channel_temp;
            var dev = channel._self;
            var deviceType = dev.device_type;
            var currentVersion = parseInt(this.getVersionSelectedChannelNumber());
            var idTypeChannelId = channel.type_channel;
            var typeChannel = this.storage.type_channel_list.get_type_channel(idTypeChannelId).type;
            var tl11 = typeChannel == 11;
            var si11_mer = typeChannel == 9;
            var mbus = typeChannel == 20;
            var td11rev2 = typeChannel&&currentVersion==1;
            var mbus_device = deviceType == 20;
            var hs = deviceType == 23;
            var um = deviceType == 25;
            var sh = deviceType == 28;
            var analog = typeChannel == 29;
            var modbus = typeChannel == 22;
            var si21_22 = deviceType == 11 || deviceType == 18;
            var si21_22rev3 = si21_22 && currentVersion >= 2;
        }
        catch(e)
        {
            return false;
        }
        return !tl11&&!si11_mer&&!mbus&&!td11rev2&&!mbus_device&&!hs&&!um&&(!sh||analog||modbus)&&!si21_22rev3;
    }
    $scope.reload_chart_temperature_new = function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_temperature_new(statistics.chart_temperature_new);
        this.charts_count++;
    }
    $scope.reload_chart_damp_new = function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_min_max_sensors(statistics.chart_damp_new, 'container_chart_damp_new', 'Влажность %', '%');
        this.charts_count++;
    }
    $scope.reload_chart_lux_new = function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_min_max_sensors(statistics.chart_lux_new, 'container_chart_lux_new', 'Освещенность lux', 'lux');
        this.charts_count++;
    }
    $scope.reload_chart_dB_new = function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_min_max_sensors(statistics.chart_dB_new, 'container_chart_dB_new', 'Шум dB', 'dB' );
        this.charts_count++;
    }
    $scope.reload_chart_CO2_new = function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_min_max_sensors(statistics.chart_CO2_new, 'container_chart_CO2_new', 'Уровень CO2', 'CO2');
        this.charts_count++;
    }
    $scope.reload_chart_temperature_multi = function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_temperature_multi(statistics.chart_temperature);
        this.charts_count++;
    }
    $scope.reload_chart_sensor_new = function (type)
    {
        if( type === undefined ) type = 5;
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_sensor_new(statistics.chart_sensor_new,type);
        this.charts_count++;
    }
    $scope.reload_chart_power_profile = function ()
    {
        var channel = this.storage.devices.get_select_channel();
        var statistics = channel.statistics;
        this.highcharts_power_profile(statistics.arr_power_profile,channel.type_meter);
        this.charts_count++;
    }
    $scope.reload_charts1 =function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_1(statistics.chart);
        this.charts_count++;
    }
    $scope.reload_charts_new = function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_new(statistics.chart);
        this.charts_count++;
    }
    $scope.reload_charts_consum= function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_consum(statistics.chart);
        this.charts_count++;
    }
    $scope.reload_charts_consum_v2= function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_consum_v2(statistics.arr_value_consum);
        this.charts_count++;
    }
    $scope.reload_charts_consum_v5= function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_consum_v5(statistics.chart_consumption);
        this.charts_count++;
    }
    $scope.reload_charts_consum_v4= function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_consum_v4(statistics.arr_value_consum_v4);
        this.charts_count++;
    }
    $scope.reload_charts4 =function ()
    {
        
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_4(statistics.chart_temperature);
        this.charts_count++;
    }
    $scope.reload_charts2 =function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_2(statistics.connect);
        this.charts_count++;
    }
    $scope.reload_charts3 =function ()
    {   
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_3(statistics.arr_value);
        this.charts_count++;
    }
    $scope.reload_charts =function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts(statistics.arr_value);
        this.charts_count++;
    }
    $scope.reload_charts_danger =function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_danger(statistics.arr_value);
        this.charts_count++;
    }
    $scope.reload_charts_danger_4 = function ()
    {
        var statistics = this.storage.devices.get_select_channel().statistics;
        this.highcharts_danger_4(statistics.arr_value_4);
        this.charts_count++;
    }
    $scope.edit_change_device = function ()
    {
        if (this.editDevice.device.device_type == 3)
        {
//            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(16);
//            this.editDevice.num_channel=1;
//            $scope.refreshSlider();
        }
        else if (this.editDevice.device.device_type == 4)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(7);
            this.editDevice.num_channel=1;
            $scope.refreshSlider();
        }
        else if (this.editDevice.device.device_type == 5)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(9);
            this.editDevice.num_channel=1;
        }
        else if (this.editDevice.device.device_type == 6)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(10);
            this.editDevice.num_channel=1;
        }
        else if (this.editDevice.device.device_type == 7)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(11);
            this.editDevice.num_channel=1;
        }
        else if (this.editDevice.device.device_type == 8)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(12);
            this.editDevice.num_channel=1;
        }
        else if (this.editDevice.device.device_type == 9)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(8);
            this.editDevice.num_channel=1;
            $scope.refreshSlider();
        }
        else if (this.editDevice.device.device_type == 10)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(13);
            this.editDevice.num_channel=1;
        }
        else if (this.editDevice.device.device_type == 12 || this.editDevice.device.device_type == 24 || this.editDevice.device.device_type == 27 )
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(14);
            this.editDevice.num_channel=1;
            if(this.editDevice.device.device_type == 24)
            {
                this.editDevice.count_rate = 4;
            }
        }
        else if (this.editDevice.device.device_type == 13 || this.editDevice.device.device_type == 17)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(15);
            this.editDevice.num_channel=1;
        }
        else if (this.editDevice.device.device_type == 14)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(17);
            this.editDevice.num_channel=1;
        }
        else if (this.editDevice.device.device_type == 15)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(18);
            this.editDevice.num_channel=1;
        }
        else if (this.editDevice.device.device_type == 23)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(23);
            this.editDevice.num_channel=1;
        }
        else if (this.editDevice.device.device_type == 25)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(25);
            this.editDevice.num_channel=1;
        }
        else if (this.editDevice.device.device_type == 26)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(26);
            this.editDevice.num_channel=1;
        }
        else if (this.editDevice.device.device_type == 31)
        {
            this.editDevice.type_channel=this.storage.type_channel_list.get_type_channel(31);
            this.editDevice.num_channel=1;
        }
        else
        {
            
        }
    }
    $scope.changeWater=function ()
    {
        if (this.editDevice.device.device_type == 9)
        {
            if (this.editDevice.water==1)
            {
               this.editDevice.color=$scope.storage.color_list.list[8];
            }
            else if (this.editDevice.water==2)
            {
                this.editDevice.color=$scope.storage.color_list.list[3];
            }
        }
        else
        {
            
        }
    }
    $scope.getColorTemperatureNew = function(history)
    {
        var channel = $scope.storage.devices.select_channel_temp;
        if( isObject(channel) && isObject(history) )
        {
            var t = history.last_temperature;
            var t_max = channel.last_max_temperature;
            var t_min = channel.last_min_temperature;
            if (t<=t_min)
            {
                return 'temperatureBlue'
            }
            else if (t>=t_max)
            {
                return 'temperatureRed'
            }
        }
        return 'temperatureNormal';
    }
    $scope.getColorDamp = function(history)
    {
        var channel = $scope.storage.devices.select_channel_temp;
        if( isObject(channel) && isObject(history) )
        {
            var t = history.last_damp;
            var t_max = channel.last_max_sensor;
            var t_min = channel.last_min_sensor;
            if (t<=t_min)
            {
                return 'temperatureBlue'
            }
            else if (t>=t_max)
            {
                return 'temperatureRed'
            }
        }
        return 'temperatureNormal';
    }
    $scope.getColorTemperature = function(t)
    {
        var channel = $scope.storage.devices.select_channel_temp;
        var t = parseFloat(t);
        var t_max = channel.max_t;
        var t_min = channel.min_t;
        if (t<=t_min)
        {
            return 'temperatureBlue'
        }
        else if (t>=t_max)
        {
            return 'temperatureRed'
        }
        else
        {
            return 'temperatureNormal'
        }
    }
    $scope.historyCss = function(history)
    {
        var dt = parseInt(history.dt);
        switch (dt) {
            case 9:
                var leaking = history.leaking;
                var breakthrough = history.breakthrough;
                var display = history.state_display;
                var hall_1 = history.hall_1;
                if (leaking||breakthrough||display||hall_1)
                {
                    return 'dangerHistory';
                }
                else
                {
                    return '';
                }
            break;
            default:
                return '';
            break;
        }
    }
    $scope.parseError= function( value, code, typeDevice)
    {
        if(typeDevice == 24)
        {
            if(code == 1)
            {
                switch (value) {
                    case 0:
                        return 'По времени'
                        break;
                    case 1:
                        return 'Охранный вход'
                        break;
                    case 2:
                        return 'Корпус вскрыт'
                        break;
                    case 3:
                        return 'Сработал датчик холла 1'
                        break;
                    case 4:
                        return 'Сработал датчик холла 2'
                        break;
                    case 5:
                        return 'Превышен лимит температуры'
                        break;
                    default:
                        return 'Неизвестная причина'    
                        break;
                }
            }
            else if(code == 2)
            {
                switch (value) {
                    case 0:
                        return 'По времени'
                        break;
                    case 1:
                        return 'Охранный вход'
                        break;
                    case 2:
                        return 'Корпус вскрыт'
                        break;
                    case 3:
                        return 'Сработал датчик холла 1'
                        break;
                    case 4:
                        return 'Сработал датчик холла 2'
                        break;
                    case 5:
                        return 'Превышен лимит температуры'
                        break;
                    default:
                        return 'Неизвестная причина'    
                        break;
                }
            }
            else if(code == 3)
            {
                switch (value) {
                    case 0:
                        return 'По времени'
                        break;
                    case 1:
                        return 'Охранный вход'
                        break;
                    case 2:
                        return 'Корпус вскрыт'
                        break;
                    case 3:
                        return 'Сработал датчик холла 1'
                        break;
                    case 4:
                        return 'Сработал датчик холла 2'
                        break;
                    case 5:
                        return 'Превышен лимит температуры'
                        break;
                    default:
                        return 'Неизвестная причина'    
                        break;
                }
            }
            else if(code == 4)
            {
                switch (value) {
                    case 0:
                        return 'По времени'
                        break;
                    case 1:
                        return 'Охранный вход'
                        break;
                    case 2:
                        return 'Корпус вскрыт'
                        break;
                    case 3:
                        return 'Сработал датчик холла 1'
                        break;
                    case 4:
                        return 'Сработал датчик холла 2'
                        break;
                    case 5:
                        return 'Превышен лимит температуры'
                        break;
                    default:
                        return 'Неизвестная причина'    
                        break;
                }
            }
            else if(code == 5)
            {
                switch (value) {
                    case 0:
                        return 'По времени'
                        break;
                    case 1:
                        return 'Охранный вход'
                        break;
                    case 2:
                        return 'Корпус вскрыт'
                        break;
                    case 3:
                        return 'Сработал датчик холла 1'
                        break;
                    case 4:
                        return 'Сработал датчик холла 2'
                        break;
                    case 5:
                        return 'Превышен лимит температуры'
                        break;
                    default:
                        return 'Неизвестная причина'    
                        break;
                }
            }
        }
        return '';
    }
    $scope.parseReason = function(r,typeDevice, channel,dt)
    {
        var reason_str = r;
        var reason = parseInt(r);
        if ( typeDevice === 3 || typeDevice === 12 )
        {
            switch (reason) {
            case 0:
                return 'По времени'
                break;
            case 1:
                return 'Охранный вход'
                break;
            case 2:
                return 'Корпус вскрыт'
                break;
            case 3:
                return 'Сработал датчик холла 1'
                break;
            case 4:
                return 'Сработал датчик холла 2'
                break;
            case 5:
                return 'Превышен лимит температуры'
                break;
            default:
                return 'Неизвестная причина'    
                break;
            }
        }
        else if(typeDevice == 'si21_22rev3')
        {
            switch (reason) {
                case 0:
                    return 'По времени'
                    break;
                case 1:
                    return 'Сработал вход №1'
                    break;
                case 2:
                    return 'Сработал вход №2'
                    break;
                case 3:
                    return 'Сработал вход №3'
                    break;
                case 4:
                    return 'Сработал вход №4'
                    break;
                case 5:
                    return 'Превышен лимит температуры'
                    break;
                default:
                    return 'Неизвестная причина'    
                    break;
            }
        }
        else if(typeDevice == 'si11rev2')
        {
            switch (reason) {
                case 0:
                    return 'По времени'
                    break;
                case 1:
                    return 'Сработал вход №1'
                    break;
                case 2:
                    return 'Сработал вход №2'
                    break;
                case 3:
                    return 'Сработал вход №3'
                    break;
                case 4:
                    return 'Сработал вход №4'
                    break;
                default:
                    return 'Неизвестная причина'    
                    break;
            }
        }
        else if (typeDevice == 28)
        {
            var nameChannel1 = 'на входе 1';
            var nameChannel2 = 'на входе 2';
            switch (reason) {
            case 1:
                return 'По времени'
                break;
            case 2:
                return 'По тревоге '+nameChannel1;
                break;
            case 3:
                return 'По тревоге '+nameChannel2;
                break;
            case 4:
                return 'По команде с конфигуратора'
                break;
            case 5:
                return 'По нажатию кнопки'
                break;
            default:
                return 'Неизвестная причина'    
                break;
            }
        }
        else if (typeDevice == 11)
        {
            switch (reason_str) 
            {
                case '00':
                    return 'По времени'
                    break;
                case '01':
                     return 'Корпус вскрыт'
                    break;
                case '10':
                    return channel.hall_1_name
                    break;
                case '11':
                    return 'Магнитный датчик 2'
                    break;
                default:
                    return 'Неизвестная причина'    
                    break;
            }
        }
        else if (typeDevice == 'GM1'|| (typeDevice == 8 && dt == 17))
        {
            if(reason == 1) return 'По времени';
            return 'Тревога';
        }
        else if (typeDevice == 8)
        {
            switch (reason) {
                case 0:
                    return 'По времени'
                    break;
                case 1:
                    return channel.name_sensor_in_1
                    break;
                case 2:
                    return channel.name_sensor_in_2
                    break;
                case 3:
                    return channel.name_sensor_out_1;
                    break;
                case 4:
                    return channel.name_sensor_out_2;
                    break;
                case 5:
                    return 'Магнитное воздействие'
                    break;
                case 6:
                    return 'Вскрытие корпуса'
                    break;
                default:
                    return 'Неизвестная причина'    
                    break;
            }
        }
        
        else if (typeDevice == 5)
        {
            switch (reason) {
                case 0:
                    return 'По времени';
                    break;
                case 1:
                    return channel.security_name;
                    break;
                case 2:
                    return channel.security_name_2;
                    break;
                case 3:
                    return 'Изменилось состояние внешнего питания';
                    break;
                case 4:
                    return 'Показания за пределами лимита';
                    break;
                case 5:
                    return 'По запросу';
                    break;
                default:
                    return 'Неизвестная причина'    
                    break;
            }
        }
        else
        {
            return 'Неизвестная причина' 
        }
    }
    $scope.saveDevice=function ()
    {
        var valid_status = this.editDevice.valid();
        if (valid_status)
        {
            var dt = parseInt(this.editDevice.device.device_type);
            var devEui = this.editDevice.device.devEui;
            var tmp = new Object();
            if ((this.editDevice.address_level_1 === undefined || this.editDevice.name_level_1 === undefined) && this.editDevice.level_1!==undefined)
            {
                this.editDevice.address_level_1 = this.editDevice.level_1.address_level_1;
                this.editDevice.name_level_1 = this.editDevice.level_1.name_level_1;
            }
            tmp.address_level_1 = this.editDevice.level_1.address_level_1;
            tmp.name_level_1 = this.editDevice.level_1.name_level_1;
            tmp.level_2 = this.editDevice.level_2;
            tmp.name = this.editDevice.name;
            tmp.num_channel = this.editDevice.num_channel;
            tmp.status = this.editDevice.status;
            tmp.color = this.editDevice.color.id;
            tmp.info_channel = this.editDevice.info_channel;
            tmp.init_value = this.editDevice.init_value;
            tmp.last_date = new Date(this.editDevice.last_date).getTime();
            tmp.date_installation = new Date(this.editDevice.date_installation).getTime();
            tmp.date_shipment = new Date(this.editDevice.date_shipment).getTime();
            tmp.type_channel = this.editDevice.type_channel.id;
            tmp.history = this.editDevice.history;
            tmp.division = this.editDevice.division;
            tmp.calib_interval = this.editDevice.calib_interval;
            tmp.ia = this.editDevice.ia;
            tmp.key = this.editDevice.key;
            tmp.mac = this.editDevice.mac;
            tmp.model = this.editDevice.model;
            tmp.serial = this.editDevice.serial;
            tmp.personal_num = this.editDevice.personal_num;
            tmp.type_meter = this.editDevice.type_meter;
            tmp.kt = this.editDevice.kt;
            tmp.security_name = this.editDevice.security_name;
            tmp.hall_1_name = this.editDevice.hall_1_name;
            tmp.hall_2_name = this.editDevice.hall_2_name;
            tmp.min_t = this.editDevice.min_t;
            tmp.max_t = this.editDevice.max_t;
            tmp.water = this.editDevice.water;
            tmp.instrument = this.editDevice.instrument;
            tmp.instrument2 = this.editDevice.instrument2;
            tmp.unit = this.editDevice.unit;
            tmp.min_v = this.editDevice.min_v;
            tmp.max_v = this.editDevice.max_v;
            tmp.min_normal_v = this.editDevice.min_normal_v;
            tmp.max_normal_v = this.editDevice.max_normal_v;
            tmp.security_name_2 = this.editDevice.security_name_2;
            tmp.sensor_name_1 = this.editDevice.sensor_name_1;
            tmp.sensor_name_2 = this.editDevice.sensor_name_2;

            for(var i = 1; i<=10; i++)
            {
                tmp[`temperature_sensor_name_${i}`] = this.editDevice[`temperature_sensor_name_${i}`];
            }

            tmp.name_sensor_in_1=this.editDevice.name_sensor_in_1;
            tmp.name_sensor_in_2=this.editDevice.name_sensor_in_2;
            tmp.name_sensor_out_1=this.editDevice.name_sensor_out_1;
            tmp.name_sensor_out_2=this.editDevice.name_sensor_out_2;
            tmp.telephones = this.editDevice.telephones;
            tmp.emails = this.editDevice.emails;
            tmp.telegram_chats = this.editDevice.telegram_chats;
            tmp.message_sms = this.editDevice.message_sms;
            tmp.message_messenger = this.editDevice.message_messenger;
            tmp.sms = this.editDevice.sms;
            tmp.email = this.editDevice.email;
            tmp.telegram = this.editDevice.telegram;
            tmp.enable_danger = this.editDevice.enable_danger;
            tmp.user_message_danger = this.editDevice.user_message_danger;
            tmp.app_message_danger = this.editDevice.app_message_danger;
            tmp.voice = this.editDevice.voice;
            tmp.voice_message = this.editDevice.voice_message;
            tmp.count_rate = this.editDevice.count_rate;
            tmp.count_phase = this.editDevice.count_phase;
            tmp.display_power_profile = this.editDevice.display_power_profile;
            tmp.relay = this.editDevice.relay;
            
            tmp.provider = this.editDevice.provider;
            tmp.typeCargo = this.editDevice.typeCargo;
            tmp.cargo = this.editDevice.cargo;
            $scope.WS.saveDevice_universal(devEui,tmp,dt,this.editDevice.version);
        }
        else
        {
            this.universalAlert('Ошибка при добавлении устройства, все поля должны быть заполнены. Проверьте корректность введенных Вами данных. ');
        } 
    }
    $scope.get_log = function ()
    {
    }
    $scope.full_select_channel = function(channel)
    {
        var validChannel = typeof channel == 'object';
        if(!validChannel) return false;
        storage.map_nav.select(channel.name_level_1,channel.address_level_1,channel.level_2);
        // $scope.storage.map_nav.set_level_1(channel.name_level_1,channel.address_level_1);
        // $scope.storage.map_nav.set_level_2(channel.level_2);
        // var scope = $scope;
        // scope.$apply(function (){
        //     scope.storage;
        // });
        $scope.select_channel(channel.devEui,channel.num_channel);
        return true;
    }
    $scope.select_channel = function(devEui,num_channel)
    {
        if( $('body').width() <= 993 ) $scope.hideLeftPanel = true;
        $scope.device_page = 0;
        this.mapMode = 'last';
        this.clearMap(); 
        if (this.command_list_cookie.get_data)
        {
            if (storage.devices.select_channel(devEui,num_channel))
            {
                var selectedChannel = storage.devices.select_channel_temp;
                storage.events.inActiveAllChannel(selectedChannel);
                $scope.selectPage(2);
                $scope.charts_count=0;
                WS.loader = true;
                for (var i=this.storage.map_nav.history_danger.length-1;i>=0 ;i--)
                {
                    if (this.storage.map_nav.history_danger[i].devEui==devEui&&this.storage.map_nav.history_danger[i].num==num_channel)
                    {
                        this.storage.map_nav.history_danger.splice(i,1);
                    }
                }
                this.storage.devices.get_channel(devEui,num_channel).danger = false;
                var validSelectedDevice = isObject(selectedChannel) && isObject(selectedChannel._self);
                
                WS.send_get_device_data_req(storage.devices.select_device_devEui,undefined,undefined,10);
                if (validSelectedDevice&&(selectedChannel._self.device_type == 12 || selectedChannel._self.device_type == 27))
                {
                    WS.send_get_device_data_req(storage.devices.select_device_devEui,storage.date_range.getStartUTC()*1000 - DAY_MS,storage.date_range.getEndUTC()*1000+DAY_MS,50000);
                }
                else
                {
                    WS.send_get_device_data_req(storage.devices.select_device_devEui,storage.date_range.getStart()*1000-DAY_MS,storage.date_range.getEnd()*1000+DAY_MS,50000);
                }
            }
            $scope.count_data = 1;
            $scope.count_data_event = 1;
            $scope.count_data_energy = 1;
            $scope.count_data_energy_archive = 1;
            $scope.count_data_slices = 1;
            $scope.count_data_journals = 1;
            $scope.count_data_history = 1;
            $scope.count_data_instant = 1;
            $scope.count_data_instant2 = 1;
            $scope.scrollToElHome();
        }
        else
        {
            this.universalAlert('Недостаточно прав');
        }
    }
    $scope.get_dop_info_min = function (channel)
    {
        var type = this.storage.type_channel_list.get_type_channel(channel.type_channel);
        if (channel.last_date && channel.calib_interval)
        {
          return moment(channel.last_date).add(channel.calib_interval,'year').format('LL');  
        }
        else
        {
            return "-";
        }
    }
    $scope.get_dop_info = function (channel)
    {
        var validDopInfo = channel.last_date&&channel.calib_interval;
        if (validDopInfo)
        {
          return "Поверка действительна до "+moment(channel.last_date).add(channel.calib_interval,'year').format('LL');  
        }
        else
        {
            return "-";
        }
    }
    $scope.parseWater = function(water)
    {
        if (water==1)
        {
            return 'Горячая'
        }
        else if (water==2)
        {
            return 'Холодная'
        }
        else
        {
            return 'Неизвестно'
        }
    }
   $scope.get_div_color = function(hex)
   {
       return "<li class='color' style='color:red;background:"+hex+"'>111</li>";
   }
    $scope.test=function(str,str2,str3)
    {
        $scope.storage = storage;
        // console.log(str,str2,str3)
        return true;
    }
    $scope.editDeviceDateShipment = function ()
    {
        var dev = this.storage.devices.select_channel_temp;
        var devEui = dev.devEui;
        var num = dev.num_channel;
        var color = storage.color_list.get_full_color(dev.color);
        var dev_type = storage.type_channel_list.get_type_channel(dev.type_channel);
        dev = $scope.storage.devices.get_device(devEui)
        $scope.editDevice = storage.devices.get_editDevice(dev,num,color,dev_type);
        $scope.editDevice.edit = true;
        $scope.saveDevice();
        $scope.select_channel(devEui,num);
        $scope.reload_full_charts();
    }
    $scope.editDeviceTypeCargo = function ()
    {
        var dev = this.storage.devices.select_channel_temp;
        var devEui = dev.devEui;
        var num = dev.num_channel;
        var color = storage.color_list.get_full_color(dev.color);
        var dev_type = storage.type_channel_list.get_type_channel(dev.type_channel);
        dev = $scope.storage.devices.get_device(devEui)
        $scope.editDevice = storage.devices.get_editDevice(dev,num,color,dev_type);
        $scope.editDevice.edit = true;
        $scope.changeTypeCargo();
        $scope.saveDevice();
        $scope.reload_full_charts();
    }
    $scope.editDeviceTextParam = function ()
    {
        var dev = this.storage.devices.select_channel_temp;
        var devEui = dev.devEui;
        var num = dev.num_channel;
        var color = storage.color_list.get_full_color(dev.color);
        var dev_type = storage.type_channel_list.get_type_channel(dev.type_channel);
        dev = $scope.storage.devices.get_device(devEui)
        $scope.editDevice = storage.devices.get_editDevice(dev,num,color,dev_type);
        $scope.editDevice.edit = true;
        $scope.saveDevice();
    }
    $scope.editDeviceDangerEnable = function ()
    {
        var dev = this.storage.devices.select_channel_temp;
        var devEui = dev.devEui;
        var num = dev.num_channel;
        var color = storage.color_list.get_full_color(dev.color);
        var dev_type = storage.type_channel_list.get_type_channel(dev.type_channel);
        dev = $scope.storage.devices.get_device(devEui)
        $scope.editDevice = storage.devices.get_editDevice(dev,num,color,dev_type);
        $scope.editDevice.edit = true;
        $scope.editDevice.enable_danger = !$scope.editDevice.enable_danger;
        $scope.saveDevice();
    }
    $scope.copy_channel_deviceEdit = function (){
        var name = this.editDevice.name;
        var num_channel = this.editDevice.num_channel;
        var devEui = this.editDevice.device.devEui;
        var dt = this.editDevice.device.device_type;
        var color = this.editDevice.color;
        $scope.editDevice = storage.devices.get_editDevice(this.editDevice.device,num_channel,color,dt);
        var version = storage.type_device_list.get_key_first_settings_type_device($scope.editDevice.device.device_type);
        if($scope.editDevice.version === undefined || $scope.editDevice.version === "") $scope.editDevice.version = version;
        $scope.editDevice.num_channel=undefined;
        $scope.editDevice.device=undefined;
        $scope.editDevice.type = 1;
        $scope.editDevice.title = "Копирование устройства "+$scope.editDevice.name;
        
        this.pageDeviceEditor = 1;
        this.editDevice.status = '1';
        $scope.check_page = '11';
        
        $scope.refreshSlider();
        $scope.changeRangeValue();
    }
    $scope.select_channel_edit = function (devEui,num,color,dev_type)
    {
        if( $('body').width() <= 993 ) $scope.hideLeftPanel = true;
        $scope.check_page = '10';
        $scope.setting_page = 0;
        $scope.editDevice = storage.devices.get_editDevice(devEui,num,color,dev_type);
        var version = storage.type_device_list.get_key_first_settings_type_device($scope.editDevice.device.device_type);
        if($scope.editDevice.version === undefined || $scope.editDevice.version === "") $scope.editDevice.version = version;
        $scope.editDevice.version = $scope.editDevice.version.toString();
        $scope.editDevice.edit = true;
        $scope.editDevice.title = "Редактирование устройства "+$scope.editDevice.name;
        $scope.refreshSlider();
        $scope.changeRangeValue();
    }
    $scope.checkSelectedChannel = function(channel)
    {
        if (storage.devices.select_device_channel==channel.num_channel&&storage.devices.select_device_devEui==channel.devEui&&this.check_page==2)
        {
            return true;
        }
        else if (this.editDevice.num_channel==channel.num_channel&&this.editDevice.device.devEui==channel.devEui&&this.check_page==10)
        {
            return true;
        }
        return false;
    }
    
    $scope.copy_channel_edit = function (devEui,num,color,dev_type){
        $scope.editDevice = storage.devices.get_editDevice(devEui,num,color,dev_type);
        $scope.editDevice.num_channel=undefined;
        $scope.editDevice.device=undefined;
        $scope.editDevice.type = 1;
        $scope.editDevice.title = "Копирование устройства "+$scope.editDevice.name;
        $scope.refreshSlider();
        $scope.changeRangeValue();
    }
    $scope.add_device = function (){
        $scope.editDevice = new edit_device();
        $scope.refreshSlider();
    }
    $scope.get_battery=function(num)
    {
        var valid = new valid_data();
        if (valid.isNumber(num))
        {
            if (num>85)
            {
                return 4;
            }
            else if (num>65)
            {
                return 3;
            }
            else if (num>45)
            {
                return 2;
            }
            else if (num>25)
            {
                return 2;
            }
            else if (num>5)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        else
        {
           return 0;
        }
    }
    $scope.backPageDeviceEditor = function ()
    {
        if (this.pageDeviceEditor==2)
        {
           this.pageDeviceEditor=1; 
        }
        else if (this.pageDeviceEditor==3)
        {
           this.pageDeviceEditor=2; 
        }
        else if (this.pageDeviceEditor==4)
        {
           if (storage.devices.get_active_channel(storage.edit_device_main.devEui).length>0)
           {
              this.pageDeviceEditor=2;  
           }
           else
           {
               this.pageDeviceEditor=3;
           }
        }
        else if (this.pageDeviceEditor==5)
        {
            if (storage.type_device_list.get_type_device(storage.edit_device_main).count_channels>1)
            {
                this.pageDeviceEditor=4;
            }
            else
            {
                this.pageDeviceEditor=3;
            }
        }
    } 
    $scope.applyTypeDevice = function ()
    {
        if (storage.edit_device_main.selected_device_type)
        {
            storage.edit_device_main.device_type = storage.edit_device_main.selected_device_type;
        }
        var newdevice = new device();
        var res = newdevice.set_device(storage.edit_device_main,storage.type_device_list.get_type_device(storage.edit_device_main.device_type));
        if (res)
        {
            var old_device = storage.devices.get_device(newdevice.devEui);
            if (old_device!=undefined&&old_device&&old_device!=false)
            {
                old_device.device_type = newdevice.device_type;
                for (var i = 0; i<newdevice.channels.length;i++)
                {
                    var newChannel = newdevice.channels[i];
                    var oldChannel = old_device.channels[i];
                    if (oldChannel===undefined||oldChannel.status===undefined)
                    {
                        old_device.channels[i] = newChannel;
                    }
                }
                for (var j = 0; j <storage.devices.full_devices_list.length;j++ )
                {
                    if (storage.devices.full_devices_list[j].devEui == newdevice.devEui)
                    {
                        storage.devices.full_devices_list[j].device_type = newdevice.device_type;
                    }
                }
            }
            else
            {
                storage.add_device_list(newdevice);
            }
        }
        var selectedDevice = storage.devices.get_device(storage.edit_device_main.devEui);
        this.editDevice.device = selectedDevice;
        this.editDevice.num_channel = undefined;
        this.editDevice.type_channel = undefined;
        if(this.editDevice.version === undefined || this.editDevice.version === '')
        {
            if(storage.edit_device_main.version === undefined || storage.edit_device_main.version === '')
            {
                this.editDevice.version = storage.type_device_list.get_key_default_settings_type_device( storage.edit_device_main.device_type, selectedDevice.appEui ).toString();
            }
            else
            {
                this.editDevice.version = storage.edit_device_main.version.toString();
            }
        }

        var noneSerial = this.editDevice.serial == undefined;
        var noneIA = this.editDevice.ia == undefined;
        var noneSN = selectedDevice.sn == undefined;
        if( noneSerial && !noneSN ) this.editDevice.serial = selectedDevice.sn;
        if( noneIA && !noneSN ) this.editDevice.ia = selectedDevice.sn;

        this.edit_change_device();
        $scope.refreshSlider();
        var count_channels = storage.type_device_list.get_type_device(selectedDevice.device_type).count_channels;
        if (count_channels>1)
        {
            this.pageDeviceEditor = 4;
        }
        else
        {
            this.pageDeviceEditor = 5;
        }
    }
    $scope.selectOriginalDevice = function ( originalDevice )
    {
        $scope.storage.edit_device_main = originalDevice;
        var activeChannels = storage.devices.get_active_channel( originalDevice.devEui );
        var deviceType = this.storage.type_device_list.get_type_device(storage.edit_device_main.device_type);
        if ( activeChannels.length > 0 && storage.edit_device_main.device_type && isObject(deviceType) )
        {
            $scope.applyTypeDevice();
            $scope.pageDeviceEditor = 4;
        }
        else
        {
            if ( !$scope.storage.edit_device_main.device_type || !isObject(deviceType) )
            {
                var recomendationDeviceType = storage.getRecommendationDeviceType();
                if ( recomendationDeviceType ) $scope.storage.edit_device_main.selected_device_type = recomendationDeviceType.id;
            }
            else
            {
                this.storage.edit_device_main.selected_device_type = this.storage.edit_device_main.device_type;
            }
            $scope.pageDeviceEditor = 3;
        }
        if( !$scope.storage.edit_device_main.version && this.storage.edit_device_main.device_type )
        {
            this.storage.edit_device_main.version = this.storage.type_device_list.get_key_default_settings_type_device( this.storage.edit_device_main.device_type, this.storage.edit_device_main.appEui );
        }
        if(this.storage.edit_device_main.version !== '' && this.storage.edit_device_main.version !== undefined)
        {
            $scope.editDevice.version = this.storage.edit_device_main.version.toString();
        }
        $scope.editDevice.dt = this.storage.edit_device_main.device_type;
        
    }
    $scope.countTypeReport = function ()
    {
        return $('.typeReport').length;
    }
    $scope.getCommentPageDeviceEditor = function ()
    {
        switch (this.pageDeviceEditor) {
            case 1:
                return 'Шаг 1/5';
                break;
            case 2:
                return 'Шаг 2/5 - Выберите радиомодем';
                break;
            case 3:
                return 'Шаг 3/5 - Выберите модель радиомодема';
                break; 
            case 4:
                return 'Шаг 4/5 - Выбор интерфейса';
                break;
            case 5:
                return 'Шаг 5/5 - Настройка интерфейса';
                break;
            default:
                return '-';
                break;
        }
    }
    $scope.showFilterDevices = function()
    {
        $scope.check_page = '12';
    }
    $scope.showDeviceEditor = function ()
    {
        this.pageDeviceEditor = 1;
        this.storage.edit_device_main = new Object();
        this.editDevice = new edit_device();
        this.editDevice.status = '1';
        $scope.setting_page = 0;
        $scope.check_page = '11';
    }
    $scope.getHeaderText  = function ()
    {
        return 'Подключение нового устройства';
    }
    
    $scope.add_device_main=function ()
    {
        this.storage.devices.clean_tick_device_original();
        $scope.storage.edit_device_main = new Object();
        $('#edit_device_main').modal('show');
    }
    $scope.edit_device_main=function(device)
    {
        this.storage.devices.clean_tick_device_original();
        var temp= $scope.storage.devices.get_device_original(device.devEui);
        temp.tick=true;
        $scope.storage.edit_device_main=temp;
        $('#edit_device_main').modal('show');
    }
    $scope.delete_device_main=function(device)
    {
        this.universalConfirm('Внимание! Данное действие необратимо.',
        'Вы точно хотите удалить '+device.devName+'?',
        ()=>{
            this.WS.clear_device(device.devEui);
        }
        );
        // if (confirm('Вы точно хотите удалить '+device.devName+'?'))
        // {
        //     this.WS.clear_device(device.devEui);
        // }
        // else
        // {
        // }
    }
    $scope.save_device_main=function ()
    {
        var device = $scope.storage.edit_device_main;
        if (this.valid.devEui(device.devEui)&&this.valid.isInt(device.device_type))
        {
            this.WS.save_device_main(device.devEui,device.device_type,device.version);
            $('#edit_device_main').modal('hide');
        }
        else
        {
            this.universalAlert('Пожалуйста заполните все поля');
        }
    }
    $scope.page_auth=function ()
    {
       delete_cookie('token');
       window.location='../auth.html';
    }
    $( function () {
        var scope = angular.element('body').scope();
        var start = moment().startOf('day');
        var end = moment().endOf('day');
        var start2 = moment().startOf('day');
        var end2 = moment().endOf('day');
        storage.date_range.setStart(start.unix());
        storage.date_range.setEnd(end.unix());
        function cb2(start2,end2,text) {
            switch (text) {
                case 'За сегодня':
                start2 = moment().startOf('day');
                end2 = moment().endOf('day');
                break;
                case 'За вчера':
                start2 = moment().subtract(1, 'days').startOf('day');
                end2 = moment().subtract(1, 'days').endOf('day');
                break;
                case 'За неделю':
                start2 = moment().subtract(6, 'days');
                end2 = moment().endOf('day');
                break;
                case 'За 30 дней':
                start2 = moment().subtract(29, 'days');
                end2 = moment().endOf('day');
                break;
                case 'За этот месяц':
                start2 = moment().startOf('month');
                end2 = moment().endOf('month');
                break;
                case 'За год':
                start2 = moment().subtract(365, 'days');
                end2 = moment().endOf('day');
                break;
                default:
                break;
            } 
            $('#reportrange2 span').html(start2.format('MMMM D, YYYY') + ' - ' + end2.format('MMMM D, YYYY'));
            var scope = angular.element('body').scope();
            scope.managerReport.date_range.setStart(start2.unix());
            scope.managerReport.date_range.setEnd(end2.unix());
        }
        scope.cb2 = cb2;
        function cb(start, end,text) {
                switch (text) {
                        case 'За сегодня':
                        start = moment().startOf('day');
                        end = moment().endOf('day');
                        break;
                        case 'За вчера':
                        start = moment().subtract(1, 'days').startOf('day');
                        end = moment().subtract(1, 'days').endOf('day');
                        break;
                        case 'За неделю':
                        start = moment().subtract(6, 'days');
                        end = moment().endOf('day');
                        break;
                        case 'За 30 дней':
                        start = moment().subtract(29, 'days');
                        end = moment().endOf('day');
                        break;
                        case 'За этот месяц':
                        start = moment().startOf('month');
                        end = moment().endOf('month');
                        break;
                        case 'За год':
                        start = moment().subtract(365, 'days');
                        end = moment().endOf('day');
                        break;
                        default:
                        
                        break;
                        } 
            $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
            storage.date_range.setStart(start.unix());
            storage.date_range.setEnd(end.unix());
            if (storage.devices.get_select_channel()!=undefined)
            {
                $scope.WS.loader=true;
                $timeout( function (){
                    var selectedChannel = $scope.storage.devices.select_channel_temp;
                    var validSelectedDevice = isObject(selectedChannel) && isObject(selectedChannel._self);
                    if (validSelectedDevice&&(selectedChannel._self.device_type == 12 || selectedChannel._self.device_type == 27))
                    {
                        $scope.WS.send_get_device_data_req(storage.devices.select_device_devEui,storage.date_range.getStartUTC()*1000-DAY_MS,storage.date_range.getEndUTC()*1000+DAY_MS,50000);
                    }
                    else
                    {
                        $scope.WS.send_get_device_data_req(storage.devices.select_device_devEui,storage.date_range.getStart()*1000-DAY_MS,storage.date_range.getEnd()*1000+DAY_MS,50000);
                    }
                },1000);
                $timeout( function (){
                    $scope.reload_full_charts();
                },1000);
            }
        }
       
         $('#reportrange2').daterangepicker({
            startDate: start2,
            endDate: end2,
            ranges: {
               'За сегодня': [moment().startOf('day'), moment().endOf('day')],
               'За вчера': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
               'За неделю': [moment().subtract(6, 'days'), moment()],
               'За 30 дней': [moment().subtract(29, 'days'), moment()],
               'За этот месяц': [moment().startOf('month'), moment().endOf('month')],
               'За год': [moment().subtract(365, 'days'), moment().endOf('day')]
            }
        }, cb2);
        cb2(start2,end2);
        $('#reportrange').daterangepicker({
            startDate: start,
            endDate: end,
            ranges: {
               'За сегодня': [moment().startOf('day'), moment().endOf('day')],
               'За вчера': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
               'За неделю': [moment().subtract(6, 'days'), moment()],
               'За 30 дней': [moment().subtract(29, 'days'), moment()],
               'За этот месяц': [moment().startOf('month'), moment().endOf('month')],
               'За год': [moment().subtract(365, 'days'), moment().endOf('day')]
            }
        }, cb);
        cb(start, end,'За сегодня');
    });
    $scope.highcharts_3 = function (data)
    {
        
    }
    $scope.lite_get_value = function ( init, value, kt, division )
    {
        var kt = kt;
        kt = this.valid.isNumber(kt)?kt:1;
        return this.my_converter.round_size(((value/division)+parseFloat(init))*kt,3);
    }
    $scope.get_value_select_channel_last = function ()
    {
        var val = storage.devices.select_channel_temp.statistics.last_sensor;
        var channel = this.storage.devices.get_select_channel();
        return this.lite_get_value(channel.init_value,val,channel.kt,storage.devices.select_channel_temp.division);
    }
    $scope.highcharts_temperature_new = function (data)
    {
        var temperatures = new Array();
        var temperaturesMin = new Array();
        var temperaturesMax = new Array();
        var min_d;
        var max_d;
        for (var i = 0; i<data.length;i++)
        {
            var item = data[i];
            var point = {
                y:item[1],
                x:item[0],
                marker:{
                    radius:3,
                    enabled:false
                }
            }
            if ( item[4] )
            {
                point.color = 'red';
                point.marker.enabled = true;
            }
            temperatures.push(point);
            temperaturesMin.push([item[0],item[2]]);
            temperaturesMax.push([item[0],item[3]]);
            if (i==0)
            {
                min_d = item[0];
            }
            if (i==data.length-1)
            {
                max_d = item[0];
            }
        }
        Highcharts.chart('container_chart_temperature_new', {
                chart: {
                    type:'line',
                    width: $('#proba').width()-5,
                    alignTicks: false,
                    zoomType: 'x'
                },
                plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
                title:{
                    style:
                         {
                             display:'none'
                         }
                },
                 rangeSelector: {
                  enabled: false
                 },
                 credits:{
                     enabled:false
                 },
                xAxis: {
                       type: 'datetime',
                       ordinal:false
                },
                yAxis: 
                {
                    title:
                    {
                        text: 'Температура  °C'
                    },
                },
                series: [
                    {
                        name: 'Температура',
                        data: temperatures,
                        type: 'spline',
                        color:'green',
                        lineWidth:2,
                        marker: { 
                          enabled: true 
                        }, 
                    },
                    { 
                        name: 'Нижний порог',
                        type: 'line', 
                        data: temperaturesMin,
                        color:'blue',
                        lineWidth:1,
                        marker: { 
                          enabled: false 
                        }, 
                        enableMouseTracking:false
                    } ,
                    { 
                        name: 'Верхний порог',
                        type: 'line', 
                        data: temperaturesMax,
                        color:'red',
                        lineWidth:1,
                        marker: { 
                          enabled: false 
                        }, 
                        enableMouseTracking:false
                    } 
                ]
            });
    }



    $scope.highcharts_min_max_sensors = function (data,container,unitText,unit)
    {
        var values = new Array();
        var valuesMin = new Array();
        var valuesMax = new Array();
        var min_d;
        var max_d;
        for (var i = 0; i<data.length;i++)
        {
            var item = data[i];
            var point = {
                y:item[1],
                x:item[0],
                marker:{
                    radius:3,
                    enabled:false
                }
            }
            if ( item[4] )
            {
                point.color = 'red';
                point.marker.enabled = true;
            }
            values.push(point);
            valuesMin.push([item[0],item[2]]);
            valuesMax.push([item[0],item[3]]);
            if (i==0)
            {
                min_d = item[0];
            }
            if (i==data.length-1)
            {
                max_d = item[0];
            }
        }
        Highcharts.chart(container, {
                chart: {
                    type:'line',
                    width: $('#proba').width()-5,
                    alignTicks: false,
                    zoomType: 'x'
                },
                plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
                title:{
                    style:
                         {
                             display:'none'
                         }
                },
                 rangeSelector: {
                  enabled: false
                 },
                 credits:{
                     enabled:false
                 },
                xAxis: {
                       type: 'datetime',
                       ordinal:false
                },
                yAxis: 
                {
                    title:
                    {
                        text: unitText
                    },
                },
                series: [
                    {
                        name: unit,
                        data: values,
                        type: 'spline',
                        color:'green',
                        lineWidth:2,
                        marker: { 
                          enabled: true 
                        }, 
                    },
                    { 
                        name: 'Нижний порог',
                        type: 'line', 
                        data: valuesMin,
                        color:'blue',
                        lineWidth:1,
                        marker: { 
                          enabled: false 
                        }, 
                        enableMouseTracking:false
                    } ,
                    { 
                        name: 'Верхний порог',
                        type: 'line', 
                        data: valuesMax,
                        color:'red',
                        lineWidth:1,
                        marker: { 
                          enabled: false 
                        }, 
                        enableMouseTracking:false
                    } 
                ]
            });
    }



    $scope.highcharts_temperature_multi = function (data)
    {
        var channel = $scope.storage.devices.select_channel_temp;
        var type = $scope.storage.type_channel_list.get_type_channel(channel.type_channel);
        var typeChannel = type.type;
        var temperatures = new Array();
        var temperatures2 = new Array();
        var name1 = 'Температура 1';
        var name2 = 'Температура 2';
        if ( typeChannel == 20 )
        {
            name1 = 'Температура в подающем трубопроводе';
            name2 = 'Температура в обратном трубопроводе';
        }
        for (var i = 0; i<data.length;i++)
        {
            var item = data[i];
            var point = {
                y:item[1],
                x:item[0]
            }
            var point2 = {
                y:item[2],
                x:item[0]
            }
            temperatures.push(point);
            temperatures2.push(point2);
        }
        Highcharts.chart('container_chart_temperature_multi', {
                chart: {
                    type:'line',
                    width: $('#proba').width()-5,
                    alignTicks: false,
                    zoomType: 'x'
                },
                plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
                title:{
                    style:
                         {
                             display:'none'
                         }
                },
                 rangeSelector: {
                  enabled: false
                 },
                 credits:{
                     enabled:false
                 },
                xAxis: {
                       type: 'datetime',
                       ordinal:false
                },
                yAxis: 
                {
                    title:
                    {
                        text: 'Температура  °C'
                    },
                },
                series: [
                    {
                        name: name1,
                        data: temperatures,
                        type: 'spline',
                        // color:'green',
                        lineWidth:2,
                        marker: { 
                          enabled: true 
                        }, 
                    },
                    {
                        name: name2,
                        data: temperatures2,
                        type: 'spline',
                        // color:'green',
                        lineWidth:2,
                        marker: { 
                          enabled: true 
                        }, 
                    },
                ]
            });
    }
    $scope.highcharts_sensor_new = function (data,type)
    {
        var sensors = new Array();
        var sensorsMin = new Array();
        var sensorsMax = new Array();
        var selectedChannel = storage.devices.select_channel_temp;
        var type = $scope.storage.type_channel_list.get_type_channel(selectedChannel.type_channel);
        var unit = type.unit;
        var tp = type == 5 || ( isObject(type) && type.type == 5);
        var sh2 = type == 29 || ( isObject(type) && type.type == 29);
        if( tp || sh2 )
        {
            unit = selectedChannel.unit;
        }
        for (var i = 0; i<data.length;i++)
        {
            var item = data[i];
            if( tp )
            {
                var value = $scope.get_value4_20mA( item[1] );
                var minValue = $scope.get_value4_20mA( item[2] );
                var maxValue = $scope.get_value4_20mA( item[3] );

                if( value !== 'Неизвестно' && minValue !== 'Неизвестно' && maxValue !== 'Неизвестно' )
                {
                    var point = {
                        y:$scope.get_value4_20mA(item[1]),
                        x:item[0],
                        marker:{
                            radius:3,
                            enabled:false
                        }
                    }
                    if ( item[4] )
                    {
                        point.color = 'red';
                        point.marker.enabled = true;
                    }
                    sensors.push( point );
                    sensorsMin.push([item[0], $scope.get_value4_20mA( item[2] ) ]);
                    sensorsMax.push([item[0], $scope.get_value4_20mA( item[3] ) ]);
                }
            }
            else if( sh2 )
            {
                var value = $scope.get_value0_21mB( item[1] );
                //var minValue = $scope.get_value0_21mB( item[2] );
                //var maxValue = $scope.get_value0_21mB( item[3] );

                if( value !== 'Неизвестно' )
                {
                    var point = {
                        y:value,
                        x:item[0],
                        marker:{
                            radius:3,
                            enabled:false
                        }
                    }
                    sensors.push( point );
                }
            }
            else
            {
                var value = item[1];
                var minValue = item[2];
                var maxValue =  item[3];
                var point = {
                    y:item[1],
                    x:item[0],
                    marker:{
                        radius:3,
                        enabled:false
                    }
                }
                if ( item[4] )
                {
                    point.color = 'red';
                    point.marker.enabled = true;
                }
                sensors.push( point );
                sensorsMin.push([item[0],  item[2] ]);
                sensorsMax.push([item[0],  item[3] ]);
            }
        }
        var series = [
            {
                name: 'Показания',
                data: sensors,
                type: 'spline',
                color:'green',
                lineWidth:2,
                marker: { 
                  enabled: true 
                }, 
            }
        ];
        if(sensorsMin.length>0)
        {
            series.push({ 
                name: 'Нижний порог',
                type: 'line', 
                data: sensorsMin,
                color:'blue',
                lineWidth:1,
                marker: { 
                  enabled: false 
                }, 
                enableMouseTracking:false
            });
        }
        if(sensorsMax.length>0)
        {
            series.push({ 
                name: 'Верхний порог',
                type: 'line', 
                data: sensorsMax,
                color:'red',
                lineWidth:1,
                marker: { 
                  enabled: false 
                }, 
                enableMouseTracking:false
            } );
        }
        Highcharts.chart('container_chart_sensor_new', {
                chart: {
                    type:'line',
                    width: $('#proba').width()-5,
                    alignTicks: false,
                    zoomType: 'x'
                },
                plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
                title:{
                    style:
                         {
                             display:'none'
                         }
                },
                 rangeSelector: {
                  enabled: false
                 },
                 credits:{
                     enabled:false
                 },
                xAxis: {
                       type: 'datetime',
                       ordinal:false
                },
                yAxis: 
                {
                    title:
                    {
                        text: 'Показания '+unit
                    },
                },
                series: series
            });
    }
    $scope.highcharts_temperature_1wire = function (data,channel)
    {
        var arr_t_0 = new Array();
        var arr_t_1 = new Array();
        var arr_t_2 = new Array();
        var arr_t_3 = new Array();
        var arr_t_4 = new Array();
        var arr_t_5 = new Array();
        var arr_t_6 = new Array();
        var arr_t_7 = new Array();
        var arr_t_8 = new Array();
        var arr_t_9 = new Array();
        var arr_t_10 = new Array();

        var visible_t_0 = false;
        var visible_t_1 = false;
        var visible_t_2 = false;
        var visible_t_3 = false;
        var visible_t_4 = false;
        var visible_t_5 = false;
        var visible_t_6 = false;
        var visible_t_7 = false;
        var visible_t_8 = false;
        var visible_t_9 = false;
        var visible_t_10 = false;

        // var min_d;
        // var max_d;
        for (var i = 0; i<data.length;i++)
        {
            var item = data[i];
            if( item[1]!==undefined && item[1] != 0 && item[1] != -150 ) visible_t_0 = true;
            arr_t_0.push([item[0],item[1]]);
            if( item[2]!==undefined && item[2] != 0 && item[2] != -150  ) visible_t_1 = true;
            arr_t_1.push([item[0],item[2]]);
            if( item[3]!==undefined && item[3] != 0 && item[3] != -150  ) visible_t_2 = true;
            arr_t_2.push([item[0],item[3]]);
            if( item[4]!==undefined && item[4] != 0 && item[4] != -150  ) visible_t_3 = true;
            arr_t_3.push([item[0],item[4]]);
            if( item[5]!==undefined && item[5] != 0 && item[5] != -150  ) visible_t_4 = true;
            arr_t_4.push([item[0],item[5]]);
            if( item[6]!==undefined && item[6] != 0 && item[6] != -150  ) visible_t_5 = true;
            arr_t_5.push([item[0],item[6]]);
            if( item[7]!==undefined && item[7] != 0 && item[7] != -150  ) visible_t_6 = true;
            arr_t_6.push([item[0],item[7]]);
            if( item[8]!==undefined && item[8] != 0 && item[8] != -150  ) visible_t_7 = true;
            arr_t_7.push([item[0],item[8]]);
            if( item[9]!==undefined && item[9] != 0 && item[9] != -150  ) visible_t_8 = true;
            arr_t_8.push([item[0],item[9]]);
            if( item[10]!==undefined && item[10] != 0 && item[10] != -150  ) visible_t_9 = true;
            arr_t_9.push([item[0],item[10]]);
            if( item[11]!==undefined && item[11] != 0 && item[11] != -150  ) visible_t_10 = true;
            arr_t_10.push([item[0],item[11]]);
            // if (i==0)
            // {
            //     min_d = item[0];
            // }
            // if (i==data.length-1)
            // {
            //     max_d = item[0];
            // }
        }
        // var min_t = storage.devices.select_channel_temp.min_t;
        // var max_t = storage.devices.select_channel_temp.max_t;
        Highcharts.chart('container_chart_temperature', {
                chart: {
                    type:'line',
                    width: $('#proba').width()-5,
                    alignTicks: false,
                    zoomType: 'x'
                },
                plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
                title:{
                    style:
                         {
                             display:'none'
                         }
                },
                 rangeSelector: {
                  enabled: false
                 },
                 credits:{
                     enabled:false
                 },
                xAxis: {
                       type: 'datetime',
                       ordinal:false
                },
                yAxis: 
                {
                    title:
                    {
                        text: 'Температура C°'
                    },
                    // plotLines: [{ 
                    //     color: 'red',
                    //     width: 1,
                    //     value: max_t,
                    //     label: {
                    //         text: 'Max',
                    //         verticalAlign: 'top',
                    //         textAlign: 'right'
                    //     }
                    // },{ 
                    //     color: 'blue',
                    //     width: 1,
                    //     value: min_t,
                    //     label: {
                    //         text: 'Min',
                    //         verticalAlign: 'bottom',
                    //         textAlign: 'right'
                    //     }
                    // }],
                },
                series: [
                    {
                        name: 'Температура внутри корпуса',
                        data: arr_t_0,
                        visible: visible_t_0
                    },
                    {
                        name: channel.temperature_sensor_name_1,
                        data: arr_t_1,
                        visible: visible_t_1
                        
                    },
                    {
                        name: channel.temperature_sensor_name_2,
                        data: arr_t_2,
                        visible: visible_t_2
                    },
                    {
                        name: channel.temperature_sensor_name_3,
                        data: arr_t_3,
                        visible: visible_t_3
                    },
                    {
                        name: channel.temperature_sensor_name_4,
                        data: arr_t_4,
                        visible: visible_t_4
                    },
                    {
                        name: channel.temperature_sensor_name_5,
                        data: arr_t_5,
                        visible: visible_t_5
                    },
                    {
                        name: channel.temperature_sensor_name_6,
                        data: arr_t_6,
                        visible: visible_t_6
                    },
                    {
                        name: channel.temperature_sensor_name_7,
                        data: arr_t_7,
                        visible: visible_t_7
                    },
                    {
                        name: channel.temperature_sensor_name_8,
                        data: arr_t_8,
                        visible: visible_t_8
                    },
                    {
                        name: channel.temperature_sensor_name_9,
                        data: arr_t_9,
                        visible: visible_t_9
                    },
                    {
                        name: channel.temperature_sensor_name_10,
                        data: arr_t_10,
                        visible: visible_t_10
                    },
                    // { 
                    //     name: 'Goal', 
                    //     type: 'scatter', 
                    //     marker: { 
                    //       enabled: false 
                    //     }, 
                    //     data: [[min_d,min_t],[max_d,max_t]],
                    //     enableMouseTracking:false,
                    //     showInLegend:false
                    // } 
                ]
            });
    }
    $scope.highcharts_temperature= function (data)
    {
        var arr_t_1 = new Array();
        var arr_t_2 = new Array();
        var min_d;
        var max_d;
        for (var i = 0; i<data.length;i++)
        {
            var item = data[i];
            arr_t_1.push([item[0],item[1]]);
            arr_t_2.push([item[0],item[2]]);
            if (i==0)
            {
                min_d = item[0];
            }
            if (i==data.length-1)
            {
                max_d = item[0];
            }
        }
        var min_t = storage.devices.select_channel_temp.min_t;
        var max_t = storage.devices.select_channel_temp.max_t;
        Highcharts.chart('container_chart_temperature', {
                chart: {
                    type:'line',
                    width: $('#proba').width()-5,
                    alignTicks: false,
                    zoomType: 'x'
                },
                plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
                title:{
                    style:
                         {
                             display:'none'
                         }
                },
                 rangeSelector: {
                  enabled: false
                 },
                 credits:{
                     enabled:false
                 },
                xAxis: {
                       type: 'datetime',
                       ordinal:false
                },
                yAxis: 
                {
                    title:
                    {
                        text: 'Температура C°'
                    },
                    plotLines: [{ 
                        color: 'red',
                        width: 1,
                        value: max_t,
                        label: {
                            text: 'Max',
                            verticalAlign: 'top',
                            textAlign: 'right'
                        }
                    },{ 
                        color: 'blue',
                        width: 1,
                        value: min_t,
                        label: {
                            text: 'Min',
                            verticalAlign: 'bottom',
                            textAlign: 'right'
                        }
                    }],
                },
                series: [
                    {
                        name: 'Температура 1',
                        data: arr_t_1
                    },
                    {
                        name: 'Температура 2',
                        data: arr_t_2
                    },
                    { 
                        name: 'Goal', 
                        type: 'scatter', 
                        marker: { 
                          enabled: false 
                        }, 
                        data: [[min_d,min_t],[max_d,max_t]],
                        enableMouseTracking:false,
                        showInLegend:false
                    } 
                ]
            });
    }
    $scope.highcharts_power_profile = function (data,type)
    {
        if(type===undefined) type = 1;
        var arr_a_p = new Array();
        var arr_a_m = new Array();
        var arr_r_p = new Array();
        var arr_r_m = new Array();
        var selectedChannel = storage.devices.select_channel_temp;
        
        for (var i = 0; i<data.length;i++)
        {
            var item = data[i];
            if (item.date_1&&item.date_2)
            {
                var date1 = ( item.date_1 - 1800 ) * 1000;
                var date2 = ( item.date_2 - 1800 ) * 1000;
                if (item.A_p_1!==undefined) arr_a_p.push([(date1),item.A_p_1]);
                if (item.A_p_2!==undefined) arr_a_p.push([(date2),item.A_p_2]);
                if (item.A_m_1!==undefined) arr_a_m.push([(date1),item.A_m_1]);
                if (item.A_m_2!==undefined) arr_a_m.push([(date2),item.A_m_2]);
                if (item.R_p_1!==undefined) arr_r_p.push([(date1),item.R_p_1]);
                if (item.R_p_2!==undefined) arr_r_p.push([(date2),item.R_p_2]);
                if (item.R_m_1!==undefined) arr_r_m.push([(date1),item.R_m_1]);
                if (item.R_m_2!==undefined) arr_r_m.push([(date2),item.R_m_2]);
            }
        }
        var arr_series = new Array();
        if (arr_a_p.length>0)
        {
            var serie = {
               name: 'A+',
               data: arr_a_p,
               pointRange:1800000,
               pointPlacement: 'between',
               groupPadding: 0,
               pointPadding: 0
            };
            if(selectedChannel._self.device_type==27) serie.name = 'P+';
            arr_series.push(serie);
        }
        if (arr_a_m.length>0)
        {
            var serie = {
               name: 'A-',
               data: arr_a_m,
               pointRange:1800000,
               pointPlacement: 'between',
               groupPadding: 0,
               pointPadding: 0
            };
            if(selectedChannel._self.device_type==27) 
            {
                serie.name = 'P-';
                serie.visible = false;
            }
            arr_series.push(serie);
        }
        if (arr_r_p.length>0)
        {
            var serie = {
               name: 'R+',
               data: arr_r_p,
               pointRange:1800000,
               pointPlacement: 'between',
               groupPadding: 0,
               pointPadding: 0
            };
            if(selectedChannel._self.device_type==27) 
            {
                serie.visible = false;
                serie.name = 'Q+';
            }
            arr_series.push(serie);
        }
        if (arr_r_m.length>0)
        {
            var serie = {
               name: 'R-',
               data: arr_r_m,
               pointRange:1800000,
               pointPlacement: 'between',
               groupPadding: 0,
               pointPadding: 0
            };
            if(selectedChannel._self.device_type==27) 
            {
                serie.name = 'Q-';
                serie.visible = false;
            }
            arr_series.push(serie);
        }
        Highcharts.chart('container_power_profile', {
           chart: {
               width: $('#proba').width()-5,
               type: 'column',
               zoomType: 'x'
           },
           plotOptions:
            {
                series:
                {
                    turboThreshold:0
                }
            },
           credits:{
                     enabled:false
                 },
           title:{
               style:
                    {
                        display:'none'
                    }
           },
            yAxis: {
                title: {
                    text: type==5?"Вт⋅ч":'Вт'
                },
                
             },
            xAxis: {
                  type: 'datetime',
                  ordinal:false,
                  tickInterval:1800000,
             },
            rangeSelector: {
             enabled: false
            },
           series: arr_series
       });
    }
    $scope.highcharts_consum_v5 = function (myData)
    {
        var tempData = new Array();
        var tempData_2 = new Array();
        var channel = $scope.storage.devices.get_select_channel();
        var type = $scope.storage.type_channel_list.get_type_channel(channel.type_channel);
        var unit = type.unit;
        var data = [];
        var antiRepeat = {};
        var myValues = {};
        for ( var i = 0; i < myData.length; i++ )
        {
            if ( !antiRepeat[myData[i][0]] )
            {
                antiRepeat[myData[i][0]] = true;
                data.push(myData[i]);  
            }
        }
        for ( var i = 1; i < data.length; i++ )
        {
            // ( data[i][0] - data[i-1][0] ) != HOUR_MS 
            var myValue = {
                x:data[i-1][0]
            };
            if ( !storage.date_range.compare( data[i][0],2 ) || !storage.date_range.compare( data[i-1][0],2 ) ) continue;
            if ( type.type == 4 )
            {
                myValue.y = this.my_converter.round_size( data[i][1]-data[i-1][1],3 );
                myValue.x_end = data[i][0];
                //tempData.push( [ data[i-1][0], this.my_converter.round_size( data[i][1]-data[i-1][1] , 4 ), data[i][0]  ] )
            }
            else if ( type.type == 8 )
            {
                // tempData.push( [ data[i-1][0], this.my_converter.round_size( data[i][1]-data[i-1][1] , 4 ), data[i][0] ] )
                myValue.y = this.my_converter.round_size( data[i][1]-data[i-1][1],3 );
                myValue.x_end = data[i][0];
            }
            else 
            {
                var kt = channel.kt;
                kt = this.valid.isNumber( kt ) ? kt : 1;
                var val = this.my_converter.round_size( ( ( ( data[i][1]-data[i-1][1] )/channel.division ) )*kt, 3 );
                myValue.y = val;
                myValue.x_end = data[i][0];
                // tempData.push( [data[i-1][0], val, data[i][0] ] );
                // console.log(data[i][3]+'-'+data[i-1][3]+'  result='+tempData[tempData.length-1][1]);
            }
            if(( data[i][0] - data[i-1][0] ) != HOUR_MS)  
            {
                myValue.color = 'red';
                tempData_2.push(myValue);
            }
            else
            {
                tempData.push(myValue);
            }
        }
        for(var i = 0; i < tempData.length; i++)
        {
            var date1 = tempData[i].x;
            var date2 = tempData[i].x_end;
            var val   = tempData[i].y;
            var color = tempData[i].color;
            tempData[i].x = convert_time_ms(date1,'no');
            tempData[i].x_end = convert_time_ms(date2,'no');

            myValues[tempData[i].x] = [ date1-get_time_zone()*1000, val, date2-get_time_zone()*1000 ];
        }
        for(var i = 0; i < tempData_2.length; i++)
        {
            var date1 = tempData_2[i].x;
            var date2 = tempData_2[i].x_end;
            var val   = tempData_2[i].y;
            var color = tempData_2[i].color;
            tempData_2[i].x = convert_time_ms(date1,'no');
            tempData_2[i].x_end = convert_time_ms(date2,'no');

            myValues[tempData_2[i].x] = [ date1-get_time_zone()*1000, val, date2-get_time_zone()*1000 ];
        }
        var arr_series = {
               name: 'Почасовое потребление',
               data: tempData,
               pointPlacement: 'between',
               groupPadding: 0,
               pointPadding: 0
        };
        var arr_series_2 = {
            name: 'Потребление остальное',
            data: tempData_2,
            pointPlacement: 'between',
            groupPadding: 0,
            pointPadding: 0,
            color:'red',
            visible:false
     };
     if(arr_series.data.length == 0) arr_series_2.visible = true;
        Highcharts.chart('container_consum_v5', {
           chart: {
               width: $('#proba').width()-5,
               type: 'column',
               zoomType: 'x'
           },
           plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
           credits:{
                     enabled:false
                 },
           title:{
               style:
                    {
                        display:'none'
                    }
           },
           tooltip: {
                useHTML: true,
                formatter: function () {
                    var text = 'Потреблено: <b>' +  this.y + unit + '</b><br>'
                    + 'В период: <br>' 
                    + 'С:&ensp;&ensp;<b>'+ moment(myValues[this.x][0]).format('LLL') + '</b><br>'
                    + 'По:&ensp;<b>'+ moment(myValues[this.x][2]).format('LLL') + '</b><br>'
                    + 'За:&ensp;<b>'+ $scope.my_converter.round_size(moment.duration(myValues[this.x][2]-myValues[this.x][0]).asMinutes(),0) + ' Минут</b><br>';
                    if(this.color === 'red')  text+='<b>ВНИМАНИЕ! Потребление не за 1 час!</b>';
                    return text;
                }
            },
            yAxis: {
                title: {
                    text: unit
                },
                
             },
            xAxis: {
                  type: 'datetime',
                  ordinal:false,
                  tickInterval:60000
             },
            rangeSelector: {
             enabled: false
            },
           series: [arr_series,arr_series_2]
       });
    }
    // $scope.highcharts_consum_v5 = function (myData)
    // {
    //     var tempData = new Array();
    //     var channel = $scope.storage.devices.get_select_channel();
    //     var type = $scope.storage.type_channel_list.get_type_channel(channel.type_channel);
    //     var unit = type.unit;
    //     var data = [];
    //     var antiRepeat = {};
    //     for ( var i = 0; i < myData.length; i++ )
    //     {
    //         if(!antiRepeat[myData[i][0]])
    //         {
    //             antiRepeat[myData[i][0]] = true;
    //             data.push(myData[i]);  
    //         }
    //     }
    //     for (var i =1; i<data.length;i++)
    //     {
    //         console.log(data[i-1][3], data[i][0] - data[i-1][0] );
    //         if( !storage.date_range.compare(data[i][0],2) || !storage.date_range.compare(data[i-1][0],2) || (data[i][0] - data[i-1][0]) != HOUR_MS ) continue;
    //         if (type.type==4)
    //         {
    //             tempData.push([data[i-1][0],this.my_converter.round_size(data[i][1]-data[i-1][1],4)])
    //         }
    //         else if (type.type==8)
    //         {
    //             tempData.push([data[i-1][0],this.my_converter.round_size(data[i][1]-data[i-1][1],4)])
    //         }
    //         else 
    //         {
    //             var kt = channel.kt;
    //             kt = this.valid.isNumber(kt)?kt:1;
    //             tempData.push([data[i-1][0],this.my_converter.round_size((((data[i][1]-data[i-1][1])/channel.division))*kt,3)]);
    //             console.log(data[i][3]+'-'+data[i-1][3]+'  result='+tempData[tempData.length-1][1]);
    //         }
    //     }
    //     for(var i = 0; i < tempData.length; i++)
    //     {
    //         tempData[i][0] = convert_time_ms(tempData[i][0],'no');
    //     }
    //     var arr_series = [{
    //            name: 'Показания',
    //            data: tempData,
    //            pointPlacement: 'between',
    //            groupPadding: 0,
    //            pointPadding: 0
    //     }];
    //     Highcharts.chart('container_consum_v5', {
    //        chart: {
    //            width: $('#proba').width()-5,
    //            type: 'column',
    //            zoomType: 'x'
    //        },
    //        plotOptions:
    //             {
    //                 series:
    //                 {
    //                     turboThreshold:0
    //                 }
    //             },
    //        credits:{
    //                  enabled:false
    //              },
    //        title:{
    //            style:
    //                 {
    //                     display:'none'
    //                 }
    //        },
    //         yAxis: {
    //             title: {
    //                 text: unit
    //             },
                
    //          },
    //         xAxis: {
    //               type: 'datetime',
    //               ordinal:false,
    //               tickInterval:60000
    //          },
    //         rangeSelector: {
    //          enabled: false
    //         },
    //        series: arr_series
    //    });
       
       
       
       
    // }
    $scope.highcharts_consum_v4 = function (data)
    {
          data = cloneArr(data);
          var channel = $scope.storage.devices.get_select_channel();
          var type = $scope.storage.type_channel_list.get_type_channel(channel.type_channel);
          var unit = type.unit; 
          var s1 = new Array();
          var s2 = new Array();
          var s3 = new Array();
          var s4 = new Array();
          var ss = new Array();
          var s1_c = new Array();
          var s2_c = new Array();
          var s3_c = new Array();
          var s4_c = new Array();
          var ss_c = new Array();
          if (type.type==7||type.type==9)
          {
            unit='кВт⋅ч';
            for (var i = 0; i<data.length; i++)
            {
                if (data[i][0]!=undefined)
                {
                    if (data[i][1]!==undefined) s1.push([data[i][0],data[i][1]]);
                    if (data[i][2]!==undefined) s2.push([data[i][0],data[i][2]]);
                    if (data[i][3]!==undefined) s3.push([data[i][0],data[i][3]]);
                    if (data[i][4]!==undefined) s4.push([data[i][0],data[i][4]]);
                    if (data[i][5]!==undefined) ss.push([data[i][0],data[i][5]]);
                }
            }
            for (var i = 1; i<s1.length; i++)
            {
                s1_c.push([s1[i][0],this.my_converter.round_size((s1[i][1]-s1[i-1][1])*channel.kt,4)]);
            }
            for (var i = 1; i<s2.length; i++)
            {
                s2_c.push([s2[i][0],this.my_converter.round_size((s2[i][1]-s2[i-1][1])*channel.kt,4)]);
            }
            for (var i = 1; i<s3.length; i++)
            {
                s3_c.push([s3[i][0],this.my_converter.round_size((s3[i][1]-s3[i-1][1])*channel.kt,4)]);
            }
            for (var i = 1; i<s4.length; i++)
            {
                s4_c.push([s4[i][0],this.my_converter.round_size((s4[i][1]-s4[i-1][1])*channel.kt,4)]);
            }
            for (var i = 1; i<ss.length; i++)
            {
                ss_c.push([ss[i][0],this.my_converter.round_size((ss[i][1]-ss[i-1][1])*channel.kt,4)]);
            }
          }
          
           $scope.highcharts_consum_v4.get=Highcharts.chart('container_consum_v4', {
                chart: {
                    type:'line',
                    width: $('#proba').width()-5,
                    alignTicks: false,
                    zoomType: 'x'
                },
                plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
                title:{
                    style:
                         {
                             display:'none'
                         }
                },
                 rangeSelector: {
                  enabled: false
                 },
                 credits:{
                     enabled:false
                 },
                xAxis: {
                       type: 'datetime',
                       ordinal:false
                },
                yAxis: {
                       title:{
                           text: unit
                       }
                },
                series: [
                    {
                        name: 'Тариф 1',
                        data: s1_c
                    },
                    {
                        name: 'Тариф 2',
                        data: s2_c
                    },
                    {
                        name: 'Тариф 3',
                        data: s3_c
                    },
                    {
                        name: 'Тариф 4',
                        data: s4_c
                    },
                    {
                        name: 'Сумма',
                        data: ss_c
                    }
                ]
            });
    }
    $scope.highcharts_1 = function (data)
    {
        var tempData = new Array();
        var channel = $scope.storage.devices.get_select_channel();
        var type = $scope.storage.type_channel_list.get_type_channel(channel.type_channel);
        var unit = type.unit;
        if (type.type==4)
        {
            for (var i =0; i<data.length;i++)
            {
                tempData.push([data[i][0],data[i][1]]);
            }
        }
        else if (type.type==5)
        {
            unit=channel.unit;
            for (var i =0; i<data.length;i++)
            {
                tempData.push([data[i][0]*1000,$scope.get_value4_20mA(data[i][1])])
            }
        }
        else if (type.type==7||type.type==9)
        {
            unit='кВт⋅ч';
            for (var i =0; i<data.length;i++)
            {
                tempData.push([data[i][0],data[i][1]*channel.kt]);
            }
        }
        else if (type.type==8)
        {
            unit='м³';
            for (var i =0; i<data.length;i++)
            {
                tempData.push([data[i][0],data[i][1]])
            }
        }
        else if (type.type==20)
        {
            unit='Wh';
            for (var i =0; i<data.length;i++)
            {
                tempData.push([data[i][0],data[i][1]])
            }
        }
        else
        {
            for (var i =0; i<data.length;i++)
            {
                var kt = channel.kt;
                kt = this.valid.isNumber(kt)?kt:1;
                tempData.push([data[i][0],this.my_converter.round_size(((data[i][1]/channel.division)+parseFloat(channel.init_value))*kt,3)])
            }
        }
        
        
        $scope.highcharts_1.get=Highcharts.stockChart('container1', {
           chart: {
               width: $('#proba').width()-5,
               alignTicks: false
           },
           plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
            rangeSelector: {
             enabled: false
            },
          xAxis: {
                  type: 'datetime',
                  ordinal:false
             },
           series: [{
               name: 'Показания в '+unit,
               data: tempData,
               dataGrouping: {
                  groupPixelWidth: 0
                }
           }
       ]
       });
    }
    $scope.highcharts_4 = function (data)
    {
        data.sort(function(a,b){
            return a[0]-b[0];
        });
        $scope.highcharts_4.get=Highcharts.stockChart('container4', {
           chart: {
               width: $('#proba').width()-5,
               alignTicks: false
           },
           plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
            rangeSelector: {
             enabled: false
            },
          
           series: [{
               name: 'Показания в C° ',
               data: data,
               dataGrouping: {
                  groupPixelWidth: 0
                },
           }
       ]
       });
    }
    $scope.highcharts = function (data)
    {
        var tempData = new Array();
        var channel = $scope.storage.devices.get_select_channel();
        var type = $scope.storage.type_channel_list.get_type_channel(channel.type_channel);
        for (var i =0; i<data.length;i++)
        {
            tempData.push([data[i][0],this.my_converter.round_size((data[i][1]/channel.division),2)]);
        }
        $scope.highcharts.get=Highcharts.stockChart('container', {
           chart: {
               width: $('#proba').width()-5,
               alignTicks: false
           },
           plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
            rangeSelector: {
             enabled: false
            },
           
           xAxis: {
               breaks:0
           },
           series: [{
               type: 'column',
               name: 'Потреблено '+type.unit +'',
               data: tempData,
               dataGrouping: {
                  groupPixelWidth: 0
                }
           },
       ]
       });
       
    }
    $scope.hideTypeDevice = function(type_device)
    {
        return !isObject( type_device ) || ( type_device.hide && !develop_mode );
    }
    $scope.highcharts_danger = function (data)
    {
        $scope.highcharts_danger.get=Highcharts.stockChart('container_danger', {
           chart: {
               width: $('#proba').width()-5,
               alignTicks: false
           },
           plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
            rangeSelector: {
             enabled: false
            },
            xAxis:
            {
                type: 'datetime',
                ordinal:false,
                breaks:0
            },
           series: [{
               type: 'column',
               name: 'Тревога',
               data: data,
               dataGrouping: { 
                  groupPixelWidth: 0
                }
           },
       ]
       });
       
    }
    $scope.highcharts_danger_4 = function (data)
    {
        var channel = $scope.storage.devices.select_channel_temp;
        var selected_type_device;
        if (channel&&channel.type_channel!==undefined)
        {
            selected_type_device = channel.type_channel;
        }
        var device = channel._self;
        var deviceType = device.device_type;
        var si21_22 = deviceType == 11 || deviceType == 18;
        var currentVersion = $scope.getVersionSelectedChannelNumber();
        var si21_22rev3 = si21_22 && currentVersion >= 2;
        var si12rev2 = si21_22 && currentVersion >= 2;
        var name0 = 'Обычное событие';
        var name1 = 'Тревожное событие';
        var name2 = 'Отклонение температуры';
        var name3 = 'Отклонение температуры и тревожное событие';
        var name4 = 'Отклонение температуры и тревожное событие';
        var name5 = 'Отклонение температуры и тревожное событие';
        var name6 = 'Отклонение температуры и тревожное событие';
        var name7 = 'Отклонение температуры и тревожное событие';
        var name8 = 'Отклонение температуры и тревожное событие';
        var name9 = 'Тревожное событие';
        var name10 = 'Тревожное событие';
        var name11= 'Тревожное событие';
        var name12 = 'Тревожное событие';
        var name13 = 'Тревожное событие';
        var name14 = 'Тревожное событие';
        var name15 = 'Тревожное событие';
        var name16 = 'Тревожное событие';
        
        var color0 = '#ccc';
        var color1 = '#fea22c';
        var color2 = '#ffeb3b';
        var color3 = '#fe2c75';
        var color4 = '#ccc';
        var color5 = '#ccc';
        var color6 = '#ccc';
        var color7 = '#ccc';
        var color8 = '#ccc';
        var color9 = '#ccc';
        var color10 = '#ccc';
        var color11 = '#ccc';
        var color12 = '#ccc';
        var color13 = '#ccc';
        var color14 = '#ccc';
        var color15 = '#ccc';
        var color16 = '#ccc';



        color9 = '#ccc';
        name10 = 'Низкий заряд АКБ';
        color10 = '#00bcd4';
        name11 = 'Постановка на охрану';
        color11 = '#aac20c';
        name12 = 'Стоп охраны датчика';
        color12 = '#2bffcc';
        name13 = 'Отключение охраны';
        color13 = '#2ac2ff';
        name14 = 'Ошибка датчика';
        color14 = '#7f6f2d';
        name15 = 'Запыленность камеры датчика';
        color15 = '#4f4000';
        name16 = 'Данные по расписанию';
        color16 = '#ccc';

        switch (selected_type_device) 
        {
            case 10:
                    name0= 'По времени';
                    name1= 'Сработал магнитый датчик 1';
                    name2= 'Сработал магнитый датчик 2';
                break;
            case 11:
                    name0= 'По времени';
                    name1= 'Сработал датчик движения';
                break;
            case 12:
                    name0= 'По времени';
                    name1= 'Сработал по тревоге';
                break;
            case 13:
                    name0= 'По времени';
                    name1= 'Задымление';
                    name2= 'Сработал магнитый датчик';
                break;
            case 9:
                    if(device.version == 1)
                    {
                        name0 = 'Обычное событие';
                        color0 = '#ccc';
                        name1 = 'По срабатыванию охранного входа 1';
                        color1 = '#2299f9';
                        name2 = 'По срабатыванию охранного входа 2';
                        color2 = '#009888';
                        name3 = 'Изменилось состояние внешнего питания';
                        color3 = '#eee333';
                        name4 = 'Измеряемый параметр вышел за пределы установленные лимитами';
                        color4 = '#ff3300';
                        name5 = 'Передача по запросу';
                        color5 = '#20c20c';
                        name6 = 'Неизвестная причина';
                        color6 = '#ff9900'; 
                    }
                    else
                    {
                        name0= 'По времени';
                        name3= 'Сработал охранный вход и неудовлетворительные показания';
                        name2= 'Неудовлетворительные показания';
                        name1= 'Сработал охранный вход';
                    }
                break;
            case 14:
                    name2= 'По запросу';
                    name3= 'Тревога';
                    name0= 'По времени';
                break;
            case 15:
                    if( device.device_type == 17 )
                    {
                        name0 = name2 = name3 = name4 = name5 = name6 = 'Тревога';
                        color0 = color2 = color3 = color4 = color5 = color6 = '#fea22c';
                        color1 = '#CCC';
                        name1 = 'Обычное событие';
                    }
                break;
            case 23:
                name0 = 'Неизвестное событие';
                color0 = '#222';
                name1 = 'Обычное событие';
                color1 = '#ccc';
                name2 = 'По срабатыванию '+ channel.security_name;
                color2 = '#2299f9';
                name3 = 'По срабатыванию '+ channel.security_name_2;
                color3 = '#009888';
                name4 = 'По срабатыванию акселерометра';
                color4 = '#eee333';
                name5 = 'По выходу влажности за установленные пороги';
                color5 = '#ff3300';
                name6 = 'По выходу температуры за установленные пороги';
                color6 = '#20c20c';
                break;

            
            case 25:
                name0 = 'Неизвестное событие';
                color0 = '#222';
                name1 = 'Текущее состояние устройства';
                color1 = '#ccc';
                name2 = 'По выходу СО2 за установленные пороги';
                color2 = '#2299f9';
                name3 = 'По выходу уровня освещенности за установленные пороги';
                color3 = '#009888';
                name4 = 'По срабатыванию акселерометра';
                color4 = '#eee333';
                name5 = 'По выходу влажности за установленные пороги';
                color5 = '#ff3300';
                name6 = 'По выходу температуры за установленные пороги';
                color6 = '#aac20c';
                name7 = 'По выходу уровня шума за определенные пороги';
                color7 = '#2bffcc';
                name8 = 'Обноружено снятие';
                color8 = '#2ac2ff';
                break;
            case 31:
                name5 = 'Тревога по обнаружению пожара';
                color5 = '#ff0000';
                name6 = 'Тест';
                color6 = '#ccc';
                name7 = 'Тревога по солидарной линии работы';
                color7 = '#c5cccc';
                name8 = 'Снятие с крепежной платформы';
                color8 = '#009888';
                name9 = 'Сброс тревоги';
                color9 = '#ccc';
                name10 = 'Низкий заряд АКБ';
                color10 = '#00bcd4';
                name11 = 'Постановка на охрану';
                color11 = '#aac20c';
                name12 = 'Стоп охраны датчика';
                color12 = '#2bffcc';
                name13 = 'Отключение охраны';
                color13 = '#2ac2ff';
                name14 = 'Ошибка датчика';
                color14 = '#7f6f2d';
                name15 = 'Запыленность камеры датчика';
                color15 = '#4f4000';
                name16 = 'Данные по расписанию';
                color16 = '#ccc';
                break;
            
            case 26:
                name2= 'По запросу';
                name3= 'Тревога';
                name0= 'По времени';
                break;

            default:

                break;
        }
        if(si12rev2)
        {
            name1= 'Тревога';
            name2= 'Тревога';
            name3= 'Тревога';
            name4= 'Тревога';
            name5= 'Превышен порог на импульсном входе';
            name6= 'Превышен порог на импульсном входе';
            name7= 'Превышен порог на импульсном входе';
            name8= 'Превышен порог на импульсном входе';
            name10= 'Изменилось состояние внешнего питания';
        }
        if(si21_22rev3)
        {
            name1= 'Тревога';
            name2= 'Отклонение температуры';
        }
       var series0 = {
           type: 'column',
            color: color0,
            name: name0,
            data: new Array(),
            cropThreshold:0,
            grouping:false,
            dataGrouping: { 
                  groupPixelWidth: 0
                }
       }
       var series1 = {
           type: 'column',
            color: color1,
            name:name1,
            data: new Array(),
            cropThreshold:0,
            grouping:false,
            dataGrouping: { 
                  groupPixelWidth: 0
                }
       }
       var series2 = {
           type: 'column',
           color: color2,
            name: name2,
            data: new Array(),
            cropThreshold:0,
            grouping:false,
            dataGrouping: { 
                  groupPixelWidth: 0
                }
       }
       
       var series3 = {
           type: 'column',
           color: color3,
            name: name3,
            data: new Array(),
            cropThreshold:0,
            grouping:false,
            dataGrouping: { 
                  groupPixelWidth: 0
                }
       }
       var series4 = {
           type: 'column',
           color: color4,
            name: name4,
            data: new Array(),
            cropThreshold:0,
            grouping:false,
            dataGrouping: { 
                  groupPixelWidth: 0
                }
       }
       var series5 = {
           type: 'column',
           color: color5,
            name: name5,
            data: new Array(),
            cropThreshold:0,
            grouping:false,
            dataGrouping: { 
                  groupPixelWidth: 0
                }
       }
       var series6 = {
           type: 'column',
           color: color6,
            name: name6,
            data: new Array(),
            cropThreshold:0,
            grouping:false,
            dataGrouping: { 
                  groupPixelWidth: 0
                }
       }
       var series7 = {
        type: 'column',
        color: color7,
         name: name7,
         data: new Array(),
         cropThreshold:0,
         grouping:false,
         dataGrouping: { 
               groupPixelWidth: 0
             }
    }
    var series8 = {
        type: 'column',
        color: color8,
         name: name8,
         data: new Array(),
         cropThreshold:0,
         grouping:false,
         dataGrouping: { 
               groupPixelWidth: 0
             }
    }
    var series9 = {
        type: 'column',
        color: color9,
         name: name9,
         data: new Array(),
         cropThreshold:0,
         grouping:false,
         dataGrouping: { 
               groupPixelWidth: 0
             }
    }
    var series10 = {
        type: 'column',
        color: color10,
         name: name10,
         data: new Array(),
         cropThreshold:0,
         grouping:false,
         dataGrouping: { 
               groupPixelWidth: 0
             }
    }
    var series11 = {
        type: 'column',
        color: color11,
         name: name11,
         data: new Array(),
         cropThreshold:0,
         grouping:false,
         dataGrouping: { 
               groupPixelWidth: 0
             }
    }
    var series12 = {
        type: 'column',
        color: color12,
         name: name12,
         data: new Array(),
         cropThreshold:0,
         grouping:false,
         dataGrouping: { 
               groupPixelWidth: 0
             }
    }
    var series13 = {
        type: 'column',
        color: color13,
         name: name13,
         data: new Array(),
         cropThreshold:0,
         grouping:false,
         dataGrouping: { 
               groupPixelWidth: 0
             }
    }
    var series14 = {
        type: 'column',
        color: color14,
         name: name14,
         data: new Array(),
         cropThreshold:0,
         grouping:false,
         dataGrouping: { 
               groupPixelWidth: 0
             }
    }
    var series15 = {
        type: 'column',
        color: color15,
         name: name15,
         data: new Array(),
         cropThreshold:0,
         grouping:false,
         dataGrouping: { 
               groupPixelWidth: 0
             }
    }
    var series16 = {
        type: 'column',
        color: color16,
         name: name16,
         data: new Array(),
         cropThreshold:0,
         grouping:false,
         dataGrouping: { 
               groupPixelWidth: 0
             }
    }
       for (var i = 0 ; i<data.length;i++)
       {
           if (data[i][2]==0)
           {
               series0.data.push([data[i][0],1]);
           }
           else if (data[i][2]==1)
           {
               series1.data.push([data[i][0],1]);
           }
           else if (data[i][2]==2)
           {
               series2.data.push([data[i][0],1]);
           }
           else if (data[i][2]==3)
           {
               series3.data.push([data[i][0],1]);
           }
           else if (data[i][2]==4)
           {
               series4.data.push([data[i][0],1]);
           }
           else if (data[i][2]==5)
           {
               series5.data.push([data[i][0],1]);
           }
           else if (data[i][2]==6)
           {
               series6.data.push([data[i][0],1]);
           }
           else if (data[i][2]==7)
           {
               series7.data.push([data[i][0],1]);
           }
           else if (data[i][2]==8)
           {
               series8.data.push([data[i][0],1]);
           }
           else if (data[i][2]==9)
           {
               series9.data.push([data[i][0],1]);
           }
           else if (data[i][2]==10)
           {
               series10.data.push([data[i][0],1]);
           }
           else if (data[i][2]==11)
           {
               series11.data.push([data[i][0],1]);
           }
           else if (data[i][2]==12)
           {
               series12.data.push([data[i][0],1]);
           }
           else if (data[i][2]==13)
           {
               series13.data.push([data[i][0],1]);
           }
           else if (data[i][2]==14)
           {
               series14.data.push([data[i][0],1]);
           }
           else if (data[i][2]==15)
           {
               series15.data.push([data[i][0],1]);
           }
           else if (data[i][2]==16)
           {
               series16.data.push([data[i][0],1]);
           }
       }
       
       
        $scope.highcharts_danger_4.get=Highcharts.stockChart('container_danger_4', {
           chart: {
               width: $('#proba').width()-5,
               type: 'column',
               zoomType: 'x',
           },
           plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
           title:{
               style:
                {
                    display:'none'
                }
           },
            rangeSelector: {
             enabled: false
            },
            xAxis:
            {
                type: 'datetime',
                ordinal:false,
                labels: {
                     enabled: false
                }
            },
           series: [series0,series1,series2,series3,series4,series5,series6,series7,series8,series9,series10,series11,series12,series13,series14,series15,series16]
       });
    }
    $scope.showModalStateSensorOut = function (n)
    {
        var channel = $scope.storage.devices.select_channel_temp;
        channel.edit_out = n;
        $('#sendDataDevice').modal('show');
    }
    $scope.change_send_command_to_device_type = function()
    {
        // var channel = $scope.storage.devices.select_channel_temp;
        // var command = channel.send_command_to_device;
        // if(command.type!=0)
        // {
        // }
        // else
        // {
        //     command.date = 0;
        // }
    }
    $scope.reset_multy_command = function()
    {
        $scope.multy_command = 0;
    }
    $scope.select_multy_command = function()
    {
        switch ($scope.multy_command) {
            case 1:
                this.control_get_info_counter_1(storage.devices.select_channel_temp.ia)
                break;
            case 2:
                if(storage.devices.select_channel_temp.type_meter == 6) this.control_get_info_counter_4(storage.devices.select_channel_temp.ia)
                else this.showModalCommands(5);
                break;
            case 3:
                this.control_get_info_counter_2(storage.devices.select_channel_temp.ia)
                break;
            case 4:
                if(storage.devices.select_channel_temp.type_meter == 6) this.control_relay(false,storage.devices.select_channel_temp.ia,2)
                else this.control_relay(false,storage.devices.select_channel_temp.ia,8)
                break;
            case 5:
                if(storage.devices.select_channel_temp.type_meter == 6) this.control_relay(true,storage.devices.select_channel_temp.ia,2)
                else this.control_relay(true,storage.devices.select_channel_temp.ia,8)
                break;
            case 6:
                this.express_send_command({cmd:7,port:5});
                break;
            case 7:
                this.showModalCommands(8);
                break;
            case 8:
                this.express_send_command({cmd:11,port:2});
                break;
            case 9:
                this.express_send_command({cmd:12,port:5});
                break;
            case 10:
                this.express_send_command({cmd:13,port:5});
                break;
            case 11:
                this.express_send_command({cmd:14,port:5});
                break;
            case 12:
                this.express_send_command({cmd:15,port:5});
                break;
            case 13:
                this.showModalCommands(25);
                break;
            
            case 14:
                this.showModalCommands(26);
                break;
            case 15:
                this.showModalCommands(27);
                break;
            case 16:
                this.showModalCommands(28);
                break;

            case 17:
                this.showModalCommands(18);
                break;    
            case 18:
                this.showModalCommands(19);
                break;
            case 19:
                this.showModalCommands(20);
                break;
            case 20:
                this.showModalCommands(21);
                break;

            default:
                break;
        }
        $scope.reset_multy_command();
    }
    $scope.valid_send_command = function()
    {
        var channel = $scope.storage.devices.select_channel_temp;
        if(!channel) return false;
        if(!channel._self) return false;
        if(channel.send_command_to_device === undefined) channel.send_command_to_device = {};
        var command = channel.send_command_to_device;
        if( channel._self.device_type == 26 )
        {
            var validV= typeof command.value === 'number' && command.value >= 0 && command.value <=100 ;
            if( command.cmd == 170 && validV )
            {
                return true
            }
        }
        if( channel._self.device_type == 24 )
        {
            if(command.cmd == 5)
            {
                if( command.type === 0 )
                {
                    return true;
                }
                // else if ( command.type === 1 && command.date && command.time )
                // {
                //     return true;
                // }
                else if ( (command.type === 2 || command.type === 1) && command.date )
                {
                    return true;
                }
            }
            else if( command.cmd == 8 )
            {
                var validSeason = typeof command.season === 'number';
                var validCode = typeof command.code === 'number';
                if( validSeason && validCode )
                {
                    return true;
                }
                
            }
            else if( command.cmd == 18 )
            {
                var validAddress = typeof command.address === 'string' && command.address.length <= 16;
                if( validAddress )
                {
                    return true;
                }
            }
            else if( command.cmd == 19 )
            {
                var validThreshold = typeof command.threshold === 'string' && !isNaN( parseInt( command.threshold ) );
                var validMinute = typeof command.minute === 'number';
                var validMode = typeof command.mode === 'number';
                
                if( validThreshold && validMinute && validMode )
                {
                    return true;
                }
            }
            else if( command.cmd == 20 )
            {
                var validThreshold = typeof command.threshold === 'string' && !isNaN( parseInt( command.threshold ) );
                var minute = parseInt(command.minute);
                var delay = parseInt(command.delay);
                var count_relay = parseInt(command.count_relay);
                var validMinute = typeof minute === 'number' && !isNaN(minute);
                var validMode = typeof command.mode === 'number';
                var validDelay = typeof delay === 'number' && !isNaN(delay);
                var validCountRelay = typeof count_relay === 'number' && !isNaN(count_relay);

                if( validThreshold && validMinute && validMode && validDelay && validCountRelay)
                {
                    return true;
                }
            }
            else if( command.cmd == 21 )
            {
                var validDate = command.date;
                var minute = parseInt(command.minute);
                var hour = parseInt(command.hour);
                var validMode = typeof command.mode === 'number';
                var validMinute = typeof minute === 'number' && !isNaN(minute);
                var validHour = typeof hour === 'number' && !isNaN(hour);
                

                if( validDate && validMinute && validHour && validMode )
                {
                    return true;
                }
            }
            else if( command.cmd == 25 )
            {
                var validMonth = typeof command.month === 'number';
                var validYear = typeof command.year === 'number';
                if( validMonth && validYear )
                {
                    return true;
                }
                
            }
            else if( command.cmd == 26 ||  command.cmd == 27 )
            {
                var validDay = typeof command.day === 'number';
                var validMonth = typeof command.month === 'number';
                var validYear = typeof command.year === 'number';
                if( validMonth && validYear && validDay )
                {
                    return true;
                }
                
            }
            else if( command.cmd == 28 )
            {
                var validJournal = typeof command.journal === 'number';
                if( validJournal )
                {
                    return true;
                }
            }
        }
        return false;
    }


    // var channel = $scope.storage.devices.select_channel_temp;
    // var devEui = $scope.storage.devices.select_device_devEui;
    // var cmd = '';
    // var s = '00';
    // if (channel.type_channel == 15)
    // {
    //     var output_number = '0'+n;
    //     var output_state = '0'+ (state?'1':'0');
    //     if (output_state=='01')
    //     {
    //         s = $scope.my_converter.intToBytes($scope.time_sensors_out_ug,2);
    //     }
    //     else
    //     {
    //         s='0000';
    //     }
    //     cmd = output_number+output_state+s;
    //     $scope.WS.send_data(cmd,devEui,true,2);
    // }
    // else
    // {
    //     if ($scope.slider_out.minValue!=undefined)
    //     {
    //         s = ($scope.slider_out.minValue).toString(16);
    //         if (s.length===1)
    //         {
    //             s = '0'+s;
    //         }
    //     }
    //     if (!state)
    //     {
    //         cmd+='040'+n;
    //     }
    //     else
    //     {
    //         cmd+='030'+n+s;
    //     }
    //     $scope.WS.send_data(cmd,devEui,true);
    // }
    // $('#sendDataDevice').modal('hide');
    $scope.forRange = function(min, max, step) {
        step = step || 1;
        var input = [];
        for (var i = min; i <= max; i += step) {
            input.push(i);
        }
        return input;
    };
    $scope.generationUUID = function()
    {
        var randomNumber = Math.random();
        var randomNumberUInt = Math.floor(randomNumber*65500)+1;
        var uuid = $scope.my_converter.intToBytes(randomNumberUInt,2);
        return uuid;
    }
    $scope.express_send_command = function(value)
    {
        if( !isObject(value) ) return;
        var channel = $scope.storage.devices.select_channel_temp;
        var command = channel.send_command_to_device;
        command.cmd = value.cmd;
        var port = value.port;
        $scope.control_send_command(true,port);
    }
    $scope.getTextResponseTariffScheduleSeasone = function()
    {
        //get text season
        var channel = this.storage.devices.select_channel_temp;
        var validResponse = isObject(channel.tariff_schedule)&&isObject(channel.tariff_schedule.response)&&isObject(channel.tariff_schedule.response.result);
        if(!validResponse) return '-';
        return channel.tariff_schedule.response.result.tariff_schedule_season_number+1;
    }
    $scope.getTextResponseTariffScheduleOther = function()
    {
        //get text other
        var channel = this.storage.devices.select_channel_temp;
        var validResponse = isObject(channel.tariff_schedule)&&isObject(channel.tariff_schedule.response)&&isObject(channel.tariff_schedule.response.result);
        if(!validResponse) return '-';
        return '(fcnt:'+channel.tariff_schedule.response.result.fcnt+',uuid:'+channel.tariff_schedule.response.result.UUID+')';
    }
    $scope.getTextResponseIndicationOther = function()
    {
        //get text other
        var channel = this.storage.devices.select_channel_temp;
        var validResponse = isObject(channel.indication)&&isObject(channel.indication.response);
        var validBlock1 = validResponse&&isObject(channel.indication.response.block1)&&channel.indication.response.block1.fcnt;
        var validBlock2 = validResponse&&isObject(channel.indication.response.block2)&&channel.indication.response.block2.fcnt;
        var validFullResponse = validBlock1 && validBlock2 && channel.indication.response.block1.UUID == channel.indication.response.block2.UUID;
        if(!validFullResponse) return '-';
        return 'UUID: '+channel.indication.request.uuid + '; Блок 1 - fcnt:'+channel.indication.response.block1.fcnt+'; Блок 2 - fcnt:'+channel.indication.response.block2.fcnt;
    }
    $scope.getTextResponseSpecialDaysOther = function()
    {
        //get text other
        var channel = this.storage.devices.select_channel_temp;
        var validResponse = isObject(channel.special_days)&&isObject(channel.special_days.response);
        var validBlock1 = validResponse&&isObject(channel.special_days.response.block1)&&channel.special_days.response.block1.fcnt;
        var validBlock2 = validResponse&&isObject(channel.special_days.response.block2)&&channel.special_days.response.block2.fcnt;
        var validFullResponse = validBlock1 && validBlock2 && channel.special_days.response.block1.UUID == channel.special_days.response.block2.UUID;
        if(!validFullResponse) return '-';
        return 'UUID: '+channel.special_days.request.uuid + '; Блок 1 - fcnt:'+channel.special_days.response.block1.fcnt+'; Блок 2 - fcnt:'+channel.special_days.response.block2.fcnt;
    }
    $scope.getTextResponseTariffScheduleCode = function()
    {
        //get text code
        var channel = this.storage.devices.select_channel_temp;
        var validResponse = isObject(channel.tariff_schedule)&&isObject(channel.tariff_schedule.response)&&isObject(channel.tariff_schedule.response.result);
        if(!validResponse) return '-';
        var code = channel.tariff_schedule.response.result.tariff_schedule_code;
        return this.parseCodeTariffSchedule(code);
    }
    $scope.getTextRequestTariffScheduleSeasone = function()
    {
        //get text season
        var channel = this.storage.devices.select_channel_temp;
        var sendedRequest = isObject(channel.tariff_schedule)&&isObject(channel.tariff_schedule.request)&&isObject(channel.tariff_schedule.request.other);
        if(!sendedRequest) return '-';
        return channel.tariff_schedule.request.other.season+1;
    }
    $scope.getParamNameTariffSchedule = function(index,param)
    {
        //get name param
        if(typeof index === 'number')
        {
            if(param == 'hour')
            {
                return `tariff_schedule_hour_end_${index}_zone`;
            }
            else if(param == 'minute')
            {
                return `tariff_schedule_minute_end_${index}_zone`;
            }
            else if(param == 'number')
            {
                return `tariff_schedule_number_${index}_zone`;
            }
        }
        return 0;
    }
    $scope.getParamNameIndication = function(index,param)
    {
        //get name param
        if(typeof index === 'number')
        {
            if(param == 'code')
            {
                return `code_page_indication_${index}`;
            }
            else if(param == 'time')
            {
                return `time_seconds_show_page_indication_${index}`;
            }
        }
        return 0;
    }
    $scope.getParamNameSpecialDays = function(index,param)
    {
        //get name param
        if(typeof index === 'number')
        {
            if(param == 'day')
            {
                return `special_day_d_${index}`;
            }
            else if(param == 'month')
            {
                return `special_day_m_${index}`;
            }
            else if(param == 'type')
            {
                return `special_day_t_${index}`;
            }
        }
        return 0;
    }
    // $scope.parseCodeIndication = function(code)
    // {

    // // 0x01 — Энергия нарастающим итогом.
    // // 0x02 — Энергия нарастающим итогом по первому тарифу.
    // // 0x03 — Энергия нарастающим итогом по второму тарифу.
    // // 0x04 — Энергия нарастающим итогом по третьему тарифу.
    // // 0x05 — Энергия нарастающим итогом по четвертому тарифу.
    // // 0x06 — Активная суммарная мощность.
    // // 0x07 — Часы.
    // // 0x08 — Дата.
    // // 0x09 — Часы с секундами.
    // // 0x0A — Версия параметризации.
    // // 0x0B — Энергия нарастающим итогом за предыдущий месяц.
    // // 0x0С — Энергия нарастающим итогом по 1-му тарифу за предыдущий месяц.
    // // 0x0D — Энергия нарастающим итогом по 2-му тарифу за предыдущий месяц.
    // // 0x0E — Энергия нарастающим итогом по 3-му тарифу за предыдущий месяц.
    // // 0x0F — Энергия нарастающим итогом по 4-му тарифу за предыдущий месяц.
    // // 0x10 — Дата предыдущего месяца.
    // // 0x11 — Активная мощность по фазе A.
    // // 0x12 — Активная мощность по фазе B.
    // // 0x13 — Активная мощность по фазе C.
    // // 0x14 — Версия ПО.
    // // 0x15 — Реактивная мощность по фазе A.
    // // 0x16 — Реактивная мощность по фазе B.
    // // 0x17 — Реактивная мощность по фазе C.
    // // 0x18 — Реактивная суммарная мощность.
    // // 0x19 — Полная мощность по фазе A.
    // // 0x1A — Полная мощность по фазе B.
    // // 0x1B — Полная мощность по фазе C.
    // // 0x1C — Полная суммарная мощность.
    // // 0x1D — Фактор мощности по фазе A.
    // // 0x1E — Фактор мощности по фазе B.
    // // 0x1F — Фактор мощности по фазе C.
    // // 0x20 — Фактор мощности суммарный.
    // // 0x21 — Частота сети.
    // // 0x22 — Напряжение в фазе A.
    // // 0x23 — Напряжение в фазе B.
    // // 0x24 — Напряжение в фазе C.
    // // 0x25 — Ток в фазе A.
    // // 0x26 — Ток в фазе B.
    // // 0x27 — Ток в фазе C.
    // // 0xFE — Конец таблицы
    // }
    $scope.parseCodeTariffSchedule = function(code)
    {
        if( code == 0 )
        {
            return 'Праздник';
        } 
        else if( code == 1 )
        {
            return 'Суббота';
        }
        else if( code == 2 )
        {
            return 'Воскресенье';
        }
        else if( code == 3 )
        {
            return 'Рабочий день';
        }
        return '-';
    }
    $scope.getTextRequestTariffScheduleCode = function()
    {
        //get text request code
        var channel = this.storage.devices.select_channel_temp;
        var sendedRequest = isObject(channel.tariff_schedule)&&isObject(channel.tariff_schedule.request)&&isObject(channel.tariff_schedule.request.other);
        if(!sendedRequest) return '-';
        var code = channel.tariff_schedule.request.other.code;
        return this.parseCodeTariffSchedule(code);
    }
    $scope.getStatusTariffSchedule = function()
    {
        //get status
        var channel = this.storage.devices.select_channel_temp;
        if(isObject(channel))
        {
           var sendedRequest = isObject(channel.tariff_schedule)&&isObject(channel.tariff_schedule.request);
           var validResponse = sendedRequest&&isObject(channel.tariff_schedule.response)&&isObject(channel.tariff_schedule.response.result);
           if(validResponse&&channel.tariff_schedule.response.result.UUID == channel.tariff_schedule.request.uuid )
           {
             return 2;
           }
           else if(sendedRequest)
           {
            return 1;
           }
        }
        return 0;
    }
    $scope.getStatusIndication = function()
    {
        //get status
        var channel = this.storage.devices.select_channel_temp;
        if(isObject(channel))
        {
           var sendedRequest = isObject(channel.indication)&&isObject(channel.indication.request);

            var validResponse = sendedRequest&&isObject(channel.indication)&&isObject(channel.indication.response);
            var validBlock1 = validResponse&&isObject(channel.indication.response.block1)&&channel.indication.response.block1.fcnt;
            var validBlock2 = validResponse&&isObject(channel.indication.response.block2)&&channel.indication.response.block2.fcnt;
            var validFullResponse = validBlock1 && validBlock2 && channel.indication.response.block1.UUID == channel.indication.response.block2.UUID;
            if(validFullResponse&&channel.indication.response.block1.UUID == channel.indication.request.uuid )
            {
                return 2;
            }
            else if(sendedRequest)
            {
                return 1;
            }
        }
        return 0;
    }
    $scope.getStatusSpecialDays = function()
    {
        //get status
        var channel = this.storage.devices.select_channel_temp;
        if(isObject(channel))
        {
           var sendedRequest = isObject(channel.special_days)&&isObject(channel.special_days.request);

            var validResponse = sendedRequest&&isObject(channel.special_days)&&isObject(channel.special_days.response);
            var validBlock1 = validResponse&&isObject(channel.special_days.response.block1)&&channel.special_days.response.block1.fcnt;
            var validBlock2 = validResponse&&isObject(channel.special_days.response.block2)&&channel.special_days.response.block2.fcnt;
            var validFullResponse = validBlock1 && validBlock2 && channel.special_days.response.block1.UUID == channel.special_days.response.block2.UUID;
            if(validFullResponse&&channel.special_days.response.block1.UUID == channel.special_days.request.uuid )
            {
                return 2;
            }
            else if(sendedRequest)
            {
                return 1;
            }
        }
        return 0;
    }
    $scope.saveTariffSchedule = function ()
    {
        //save
        var channel = this.storage.devices.select_channel_temp;
        var command = channel.send_command_to_device;
        command.cmd = 22;
        var port = 8;
        command.tariff_schedule = channel.tariff_schedule.response.edit;
        $scope.control_send_command( true, port );
    }
    $scope.saveIndication = function ()
    {
        //save
        var channel = this.storage.devices.select_channel_temp;
        var command = channel.send_command_to_device;
        command.cmd = 16;
        var port = 8;
        command.indication = channel.indication.response.edit;
        $scope.control_send_command( true, port );
    }
    $scope.saveSpecialDays = function ()
    {
        //save
        var channel = this.storage.devices.select_channel_temp;
        var command = channel.send_command_to_device;
        command.cmd = 23;
        var port = 8;
        command.special_days = channel.special_days.response.edit;
        $scope.control_send_command( true, port );
    }
    $scope.refreshTariffSchedule = function()
    {
        // refresh
        var channel = $scope.storage.devices.select_channel_temp;
        channel.send_command_to_device.cmd = 8;
        channel.send_command_to_device.season = channel.tariff_schedule.request.other.season;
        channel.send_command_to_device.code = channel.tariff_schedule.request.other.code;
        this.control_send_command(true,5);
    }
    $scope.control_send_command = function( ack, port )
    {
        if( typeof ack !== 'boolean' ) ack = true;
        if( typeof port !== 'number' ) port = 2;
        var channel = $scope.storage.devices.select_channel_temp;
        if(channel.send_command_to_device === undefined) channel.send_command_to_device = {};
        var command = channel.send_command_to_device;
        var hex = '';
        try
        {
            var devEui = channel._self.devEui;
            var uuid = $scope.generationUUID();
            if( channel._self.device_type == 26 )
            {
                if( command.cmd == 170 )
                {
                    hex+=$scope.my_converter.intToBytes(command.cmd,1);
                    hex+=$scope.my_converter.intToBytes(command.value,1);
                    $scope.WS.send_data(hex,devEui,ack,port);
                }
            }
            if( channel._self.device_type == 24 )
            {
                var ia = channel.ia;
                hex+=$scope.my_converter.intToBytes(command.cmd,1);
                if( command.cmd == 5 )
                {
                    hex+=$scope.my_converter.intToBytes(ia,4);
                    hex+=$scope.my_converter.intToBytes(command.type,1);
                    if( command.type === 0 )
                    {
                        hex+=$scope.my_converter.intToBytes(0,4);
                        hex+=uuid;
                        $scope.WS.send_data(hex,devEui,ack,port);
                    }
                    // else if ( command.type === 1 && command.date && command.time )
                    // {
                    //     var date = command.date.getTime();
                    //     // var time = command.time.getTime() + 25200000;
                    //     var datetime = date;
                    //     var unix_datetime = moment(datetime).unix();
                    //     hex+=$scope.my_converter.intToBytes(unix_datetime,4);
                    //     hex+=uuid;
                    //     $scope.WS.send_data(hex,devEui,ack,port);
                    // }
                    else if ( ( command.type === 2 || command.type === 1 ) && command.date )
                    {
                        var date = command.date.getTime();
                        var datetime = date;
                        var unix_datetime = moment(datetime).unix() + get_time_zone();
                        hex+=$scope.my_converter.intToBytes(unix_datetime,4);
                        hex+=uuid;
                        $scope.WS.send_data(hex,devEui,ack,port);
                    }
                }
                else if( command.cmd == 8 )
                {
                    hex+=$scope.my_converter.intToBytes(ia,4);
                    hex+=$scope.my_converter.intToBytes(command.season,1);
                    hex+=$scope.my_converter.intToBytes(command.code,1);
                    hex+=uuid;
                    port = 5;
                    if(!channel.tariff_schedule)
                    {
                        channel.tariff_schedule = {};
                    }
                    channel.tariff_schedule.request = {
                        hex:hex,
                        port:port,
                        ack:ack,
                        devEui:devEui,
                        uuid:uuid,
                        other:
                        {
                            ia:ia,
                            season:command.season,
                            code:command.code
                        }
                    };
                    channel.tariff_schedule.response = {};
                    $scope.WS.send_data(hex,devEui,ack,port);
                }
                else if( command.cmd == 7 )
                {
                    hex+=$scope.my_converter.intToBytes(ia,4);
                    hex+=uuid;
                    port = 5;
                    if(!channel.special_days)
                    {
                        channel.special_days = {};
                    }
                    channel.special_days.request = {
                        hex:hex,
                        port:port,
                        ack:ack,
                        devEui:devEui,
                        uuid:uuid
                    };
                    $scope.WS.send_data(hex,devEui,ack,port);
                }
                else if( command.cmd == 12 )
                {
                    hex+=uuid;
                    port = 5;
                    if(!channel.indication)
                    {
                        channel.indication = {};
                    }
                    channel.indication.request = {
                        hex:hex,
                        port:port,
                        ack:ack,
                        devEui:devEui,
                        uuid:uuid
                    };
                    // channel.indication.response = {};
                    $scope.WS.send_data(hex,devEui,ack,port);
                }


                else if( command.cmd == 18 )
                {
                    hex+=$scope.my_converter.intToBytes(ia,4);
                    var address = command.address;
                    var chars = [];
                    for(var i = 0; i < 16; i++)
                    {
                        var char = address.charCodeAt(i);
                        if(!isNaN(char))
                        {
                            if( char > 255 || char < 0 ) char = 36;
                            var hex_char = $scope.my_converter.intToBytes(char,1);
                            if(hex_char.length === 1) '0' + hex_char;
                            else if(hex_char.length === 2) chars.push(hex_char);
                            else chars.push('24');
                        }
                        else
                        {
                            chars.push('20');
                        }
                    }
                    // chars = chars.reverse();
                    var char_hex = chars.join('');
                    hex+=char_hex;
                    hex+=uuid;
                    port = 8;
                    $scope.WS.send_data(hex,devEui,ack,port);
                }
                else if( command.cmd == 19 )
                {
                    hex+=$scope.my_converter.intToBytes(ia,4);
                    hex+=$scope.my_converter.intToBytes(command.threshold,4);
                    hex+=$scope.my_converter.intToBytes(command.minute,1);
                    hex+=$scope.my_converter.intToBytes(command.mode,1);
                    hex+=uuid;
                    port = 8;
                    $scope.WS.send_data(hex,devEui,ack,port);
                }
                else if( command.cmd == 20 )
                {
                    hex+=$scope.my_converter.intToBytes(ia,4);
                    hex+=$scope.my_converter.intToBytes(command.threshold,4);
                    hex+=$scope.my_converter.intToBytes(command.minute,1);
                    hex+=$scope.my_converter.intToBytes(command.mode,1);
                    hex+=$scope.my_converter.intToBytes(command.delay,1);
                    hex+=$scope.my_converter.intToBytes(command.count_relay,1);
                    hex+=uuid;
                    port = 8;
                    $scope.WS.send_data(hex,devEui,ack,port);
                }
                else if( command.cmd == 21 )
                {
                    var datetime = moment(command.date).set({h:command.hour,m:command.minute}).unix() + get_time_zone();
                    hex+=$scope.my_converter.intToBytes(datetime,4);
                    hex+=$scope.my_converter.intToBytes(command.mode,1);
                    hex+=uuid;
                    port = 8;
                    $scope.WS.send_data(hex,devEui,ack,port);
                }

                else if( command.cmd == 11 || command.cmd == 12 || command.cmd == 13 || command.cmd == 14 || command.cmd == 15 )
                {
                    hex+=uuid;
                    $scope.WS.send_data(hex,devEui,ack,port);
                }
                else if( command.cmd == 22 )
                {
                    var tariff_schedule = command.tariff_schedule;
                    hex+=$scope.my_converter.intToBytes(tariff_schedule.tariff_schedule_season_number,1);
                    hex+=$scope.my_converter.intToBytes(tariff_schedule.tariff_schedule_code,1);
                    for( var i = 1; i <= 15; i++  )
                    {
                        hex+=$scope.my_converter.intToBytes(tariff_schedule[`tariff_schedule_minute_end_${i}_zone`],1);
                        hex+=$scope.my_converter.intToBytes(tariff_schedule[`tariff_schedule_hour_end_${i}_zone`],1);
                        hex+=$scope.my_converter.intToBytes(tariff_schedule[`tariff_schedule_number_${i}_zone`],1);
                    }
                    hex+=uuid;
                    $scope.WS.send_data(hex,devEui,ack,port);
                }
                else if( command.cmd == 16 || command.cmd == 17 )
                {
                    var indication = command.indication;
                    hex=$scope.my_converter.intToBytes(16,1);
                    hex+=$scope.my_converter.intToBytes(ia,4);
                    for( var i = 1; i <= 15; i++  )
                    {
                        hex+=$scope.my_converter.intToBytes(indication[`code_page_indication_${i}`],1);
                        hex+=$scope.my_converter.intToBytes(indication[`time_seconds_show_page_indication_${i}`],1);
                    }
                    hex+=uuid;
                    var hex1 = hex;
                    // $scope.WS.send_data(hex,devEui,ack,port);
                    hex=$scope.my_converter.intToBytes(17,1);
                    hex+=$scope.my_converter.intToBytes(ia,4);
                    for( var i = 16; i <= 31; i++  )
                    {
                        hex+=$scope.my_converter.intToBytes(indication[`code_page_indication_${i}`],1);
                        hex+=$scope.my_converter.intToBytes(indication[`time_seconds_show_page_indication_${i}`],1);
                    }
                    hex+=uuid;
                    var hex2 = hex;
                    $scope.WS.send_data_multy_kostil([hex1,hex2],devEui,ack,port);
                    // $scope.WS.send_data(hex,devEui,ack,port);
                }
                else if( command.cmd == 23 || command.cmd == 24 )
                {
                    var special_days = command.special_days;
                    hex=$scope.my_converter.intToBytes(23,1);
                    for( var i = 1; i <= 16; i++  )
                    {
                        hex+=$scope.my_converter.intToBytes(special_days[`special_day_d_${i}`],1);
                        hex+=$scope.my_converter.intToBytes(special_days[`special_day_m_${i}`],1);
                        hex+=$scope.my_converter.intToBytes(special_days[`special_day_t_${i}`],1);
                    }
                    hex+=uuid;
                    var hex1 = hex;
                    // $scope.WS.send_data(hex,devEui,ack,port);
                    hex=$scope.my_converter.intToBytes(24,1);
                    // hex+=$scope.my_converter.intToBytes(ia,4);
                    for( var i = 17; i <= 31; i++  )
                    {
                        hex+=$scope.my_converter.intToBytes(special_days[`special_day_d_${i}`],1);
                        hex+=$scope.my_converter.intToBytes(special_days[`special_day_m_${i}`],1);
                        hex+=$scope.my_converter.intToBytes(special_days[`special_day_t_${i}`],1);
                    }
                    hex+=uuid;
                    var hex2 = hex;
                    $scope.WS.send_data_multy_kostil([hex1,hex2],devEui,ack,port);
                    // $scope.WS.send_data(hex,devEui,ack,port);
                }
                else if( command.cmd == 25 )
                {
                    // hex+=$scope.my_converter.intToBytes(ia,4);
                    hex+=$scope.my_converter.intToBytes(command.month,1);
                    hex+=$scope.my_converter.intToBytes(command.year,1);
                    hex+=uuid;
                    port = 6;
                    $scope.WS.send_data(hex,devEui,ack,port);
                }
                else if( command.cmd == 26 || command.cmd == 27 )
                {
                    // hex+=$scope.my_converter.intToBytes(ia,4);
                    hex+=$scope.my_converter.intToBytes(command.day,1);
                    hex+=$scope.my_converter.intToBytes(command.month,1);
                    hex+=$scope.my_converter.intToBytes(command.year,1);
                    hex+=uuid;
                    port = 6;
                    $scope.WS.send_data(hex,devEui,ack,port);
                }
                else if( command.cmd == 28 )
                {
                    // hex+=$scope.my_converter.intToBytes(ia,4);
                    hex+=$scope.my_converter.intToBytes(command.journal,1);
                    hex+=uuid;
                    port = 7;
                    $scope.WS.send_data(hex,devEui,ack,port);
                }
                else
                {
                    hex+=$scope.my_converter.intToBytes(ia,4);
                    //тип пакета, сетевой адрес, uuid
                    var validCmd = typeof command.cmd == 'number';
                    if(validCmd)
                    {
                        hex+=uuid;
                        $scope.WS.send_data(hex,devEui,ack,port);
                    }
                }
            }
        }
        catch(e)
        {
            this.universalAlert('Команду не удалось отправить, произошла ошибка! ERROR: 561','Ошибка!');
            console.log(e);
        }
        finally
        {
            $('#sendCommandDevice').modal('hide');
            return;
        }
    }
    
    $scope.showModalCommands = function (n)
    {
        var channel = $scope.storage.devices.select_channel_temp;
        if(channel.send_command_to_device === undefined) channel.send_command_to_device = {};
        channel.send_command_to_device.cmd = n;
        if(channel._self.device_type == 24 && n == 5 )
        {
            channel.send_command_to_device.type = 0;
            // channel.send_command_to_device.date = 0;
            // channel.send_command_to_device.time = 0;
        }
        $('#sendCommandDevice').modal('show');
    }
    $scope.getSelectEditChannelName = function ()
    {
        return $scope.storage.devices.select_channel_temp['sensor_name_'+$scope.storage.devices.select_channel_temp.edit_out];
    }
    $scope.control_get_data = function ()
    {
         var devEui = $scope.storage.devices.select_device_devEui;
         var cmd = '02';
         $scope.WS.send_data(cmd,devEui,true);
    }
    $scope.control_relay = function (currentState,ia,port,typeMeter)
    {
        if(port === undefined) port = 2;
        var devEui = $scope.storage.devices.select_device_devEui;
        var ia = $scope.my_converter.intToBytes(ia,4);
        var state = currentState?"00":'01';
        var uuid = $scope.generationUUID();
        var cmd = '06'+ia+state+uuid;
        var message = '';
        if (state=='00')
        {
            message = 'Вы уверены, что хотите ограничить подачу энергии?';
        }
        else
        {
            message = 'Вы уверены, что хотите возобновить подачу энергии?';
        }
        this.universalConfirm('Внимание!',
        message,
        ()=>{
            $scope.WS.send_data(cmd,devEui,true,port);
        }
        );
        // if (confirm(message)) $scope.WS.send_data(cmd,devEui,true,port);
    }
    $scope.control_get_info_counter_4 = function (ia)
    {
        var devEui = $scope.storage.devices.select_device_devEui;
        var ia = $scope.my_converter.intToBytes(ia,4);
        var uuid = '0ff0';
        var cmd_3 = '05'+ia+'0000000000'+uuid;
        $scope.WS.send_data(cmd_3,devEui,true);
    }
    $scope.control_get_info_counter_1 = function (ia)
    {
        var devEui = $scope.storage.devices.select_device_devEui;
        var ia = $scope.my_converter.intToBytes(ia,4);
        var uuid = $scope.generationUUID();
        var cmd_1 = '02'+ia+uuid;
        $scope.WS.send_data(cmd_1,devEui,true);
    }
    $scope.control_get_info_counter_2 = function (ia)
    {
        var devEui = $scope.storage.devices.select_device_devEui;
        var ia = $scope.my_converter.intToBytes(ia,4);
        var uuid = $scope.generationUUID();
        var cmd_2 = '03'+ia+uuid;
        $scope.WS.send_data(cmd_2,devEui,true);
    }
    
    
    $scope.control_sensor_out = function (n,state)
    {
        var channel = $scope.storage.devices.select_channel_temp;
        var devEui = $scope.storage.devices.select_device_devEui;
        var cmd = '';
        var s = '00';
        if (channel.type_channel == 15)
        {
            var output_number = '0'+n;
            var output_state = '0'+ (state?'1':'0');
            if (output_state=='01')
            {
                s = $scope.my_converter.intToBytes($scope.time_sensors_out_ug,2);
            }
            else
            {
                s='0000';
            }
            cmd = output_number+output_state+s;
            $scope.WS.send_data(cmd,devEui,true,2);
        }
        else if(channel.type_channel == 20)
        {
            if ($scope.slider_out.minValue!=undefined)
            {
                s = ($scope.slider_out.minValue).toString(16);
                if (s.length===1)
                {
                    s = '0'+s;
                }
            }
            if (!state)
            {
                cmd+='050'+n;
            }
            else
            {
                cmd+='030'+n+s;
            }
            $scope.WS.send_data(cmd,devEui,true);
        }
        else
        {
            if ($scope.slider_out.minValue!=undefined)
            {
                s = ($scope.slider_out.minValue).toString(16);
                if (s.length===1)
                {
                    s = '0'+s;
                }
            }
            if (!state)
            {
                cmd+='040'+n;
            }
            else
            {
                cmd+='030'+n+s;
            }
            $scope.WS.send_data(cmd,devEui,true);
        }
        $('#sendDataDevice').modal('hide');
    }
    $scope.unlock_counter = function ()
    {
        var devEui = $scope.storage.devices.select_device_devEui;
        $scope.WS.send_data('02',devEui,true);
        
    }
    $scope.objectToArray = function (obj) 
    {
        var arr = new Array();
        angular.forEach(obj, function (val, key) 
        {
            arr.push(val);
        });
        return arr;
    };
    $scope.highcharts_2 = function (connect)
    {
        if (connect.length<1)
        {
            return false
        }
       connect.sort(function(a,b){
             return a.date-b.date;
         });
         connect[0].date>connect[connect.length-1].date?connect.reverse():connect;
       var date = new Array();
       var rssi = new Array();
       var snr = new Array();
       for (var i = 0; i <connect.length;i++)
       {
           date.push(connect[i].date+get_time_zone()*1000);
           rssi.push([connect[i].date+get_time_zone()*1000,connect[i].rssi]);
           snr.push([connect[i].date+get_time_zone()*1000,connect[i].snr]);
       }
        Highcharts.chart('container2', {
           chart: {
               width: $('#proba').width()-5,
               type: 'column',
               zoomType: 'x'
           },
           plotOptions:
                {
                    series:
                    {
                        turboThreshold:0
                    }
                },
           title:{
               style:
                    {
                        display:'none'
                    }
           },
            yAxis: {
                title: {
                    text: "dB"
                }
             },
            xAxis: {
                  type: 'datetime',
                  ordinal:false,
                  labels: {
                     enabled: false
                  }
             },
            rangeSelector: {
             enabled: false
            },

           series: [{
               type: 'column',
               name: 'Мощность сигнала (RSSI)',
               data: rssi
           },
           {
               type: 'column',
               name: 'Отношение сигнал/шум (SNR)',
               data: snr
           }]
       });
    };
    $scope.downloadHistory = function ()
    {
        var channel = this.storage.devices.select_channel_temp;
        $('#History').tableExport({type:'excel',fileName:moment().format('DD.MM.YY HH.mm')+" Отчет о перевозке "+channel.name+"("+channel.cargo+") "+moment().format("DD MMMM YYYY"),htmlContent:true,mso:{fileFormat:'xlshtml',worksheetName:channel.name}});
    }
    $scope.downloadTable = function(table,nameTable,nameList)
    {
        var channel = this.storage.devices.select_channel_temp;
        $('#'+table).tableExport({type:'excel',fileName:moment().format('DD.MM.YY HH.mm')+' '+nameTable,htmlContent:true,mso:{fileFormat:'xlshtml',worksheetName:nameList}});
    }
    //REPORTS!--------------------------------------------
    $scope.downloadReport = function ()
    {
        var report = this.managerReport.report;
        $('#report').tableExport({type:'excel',fileName:moment().format('DD.MM.YY HH.mm')+' '+report.info.nameFile,htmlContent:true,mso:{fileFormat:'xlshtml',worksheetName:this.managerReport.selectedObject.name}});
    }
    $scope.generateReport = function ()
    {
        try 
        {
            $('#reportProgress').modal('show');
            this.managerReport.startFormingReport();
            this.managerReport.nextPage();
            var devEui = this.managerReport.firstChannel.devEui;
            var start = this.managerReport.date_range.getStart()*1000;
            var end = this.managerReport.date_range.getEnd()*1000;
            var validSelectedDevice = isObject(this.managerReport.firstChannel) && isObject(this.managerReport.firstChannel._self);
            if (validSelectedDevice&&(this.managerReport.firstChannel._self.device_type == 12||this.managerReport.firstChannel._self.device_type == 24||this.managerReport.firstChannel._self.device_type == 27))
            {
                start = start - moment().utcOffset()*60*1000-DAY_MS;
                end = end - moment().utcOffset()*60*1000+DAY_MS;
            }
            switch (this.managerReport.selectedType.id) {
                case 1:
                    WS.send_get_device_data_req(devEui,start,end+HOUR_MS,50000,2);
                    break;
                case 2:
                    WS.send_get_device_data_req(devEui,undefined,undefined,50,2);
                    break;    
                case 3:
                    WS.send_get_device_data_req(devEui,start,end,50000,2);
                    break;
                case 4:
                    WS.send_get_device_data_req(devEui,start,end,50000,2);
                    break;
                case 5:
                    WS.send_get_device_data_req(devEui,start,end,50000,2);
                    break;
                case 6:
                    break;
                case 7:
                    WS.send_get_device_data_req(devEui,undefined,undefined,50,2);
                    break;
                default:
                    break;
            }
            return;
        } 
        catch (e) 
        {
            this.universalAlert(e);  
        }
    }
})
        .filter('filter_level_2_list',function (){
            return function(items,data)
            {
                var level_1 = data[0];
                var list = data[1];
                var res = new Array();
                var validL1 = level_1&& isObject(level_1) &&level_1.name_level_1!==undefined&&level_1.address_level_1!==undefined;
                if (validL1)
                {
                    var nameL1 = level_1.name_level_1;
                    var addressL1 = level_1.address_level_1;
                    var hashL1 = md5(nameL1+addressL1);
                    var l1 = list[hashL1];
                    if ( l1 && isObject(l1) && l1.list && isObject(l1.list) )
                    {
                        for (var key in l1.list)
                        {
                            var l2 = l1.list[key];
                            if ( l2 && isObject(l2) && l2.name )
                            {
                                res.push(l2.name);
                            }
                        }
                        return res;
                    }
                }
                return items;
            }   
        })
        .filter('filter_history',function (){
    return function(items,data)
    {
        try
        {
            var date_range = data[0];
            //Тип устройства
            var type = data[1];
            var type_package = data[2];
            var selectedChannel = data[3];
            var temp = new Array();
            var tmp_o = new Object();
            var tempObject = new Object();

            var validSelectedChannel = isObject(selectedChannel);

            var channelImpulse    = type == 1;
            var channelDanger     = type == 2;
            var channelTD11       = type == 3;
            var channelSVE        = type == 4;
            var channelTP11       = type == 5;
            var channelSMART      = type == 6;
            var channelUE         = type == 7;
            var channelUG         = type == 8;
            var channelSi13Merc   = type == 9;
            var channelLM11       = type == 10;
            var channelSRC        = type == 26;
            var channelTL11       = type == 11;
            var channelMBUS       = type == 20;
            var channelTherm      = type == 30;
            var channelSi13ModBus = type == 22;
            var channelHS         = type == 23;
            var channelUM         = type == 25;
            var channel1Wire      = type == 28;
            var channelAnalogue   = type == 29;
            
            for (var i = 0; i<items.length;i++)
            {
                var history = items[i];
                var version = history.version;
                var currentVersion = parseInt(version);
                var all = type_package == 'all';
                var correctTypePackage = type_package == history.type;
                var packageJournalSPBZIP = history.type >= 19 && history.type <= 31;
                var correctTypeArchiveSPBZIP = type_package == 16 && ( correctTypePackage ||  history.type == 17);
                var correctJournalSPBZIP = type_package == 19 && ( correctTypePackage ||  packageJournalSPBZIP);
                var currentAddress = parseInt(`0x${history.address}`);

                var validTs = history.ts != undefined;
                var validTime = history.time != undefined;
                var correctTs = validTs && date_range.compare( history.ts );
                var correctTime = validTime && date_range.compare_unix( history.time );

                var si11 = history.dt == 1;
                var si12 = history.dt == 2;
                var si13 = history.dt == 3;
                var si22 = history.dt == 18;
                var td11 = history.dt == 4;
                var si21 = history.dt == 11;
                var ue   = history.dt == 12;
                var ue_spbzip   = history.dt == 24;
                var ue_merc   = history.dt == 27;
                var mbus1 = history.dt == 20;
                var mbus2 = history.dt == 21;
                var ss   = history.dt == 10;
                var sve  = history.dt == 9;
                var sh02  = history.dt == 28;
                var ss2   = history.dt == 31;
                

                var addedHistoryWithTs = tempObject[history.ts] !== undefined;
                var addedHistoryWithTime = tempObject[history.time] !== undefined;

                if (si21 || si22) 
                {
                    if( currentVersion >= 2 )
                    {
                        var checkNumChannel = validSelectedChannel && ( history.reason == selectedChannel.num_channel );
                        if ( all && correctTs && !addedHistoryWithTs )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                        else if ( !all && channelImpulse && correctTime && !addedHistoryWithTime && history.port == 2 )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                        else if ( !all && channelDanger && correctTime && !addedHistoryWithTime && (checkNumChannel || history.reason == 5) && history.port == 2 )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                    }
                    else
                    {
                        var checkNumChannel = validSelectedChannel && ( history.num_channel == selectedChannel.num_channel );
                        if ( all && correctTs && !addedHistoryWithTs )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                        else if ( !all && channelImpulse && history.type == 1 && correctTime && !addedHistoryWithTime && history.port == 2 )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                        else if ( !all && channelDanger && history.type == 2 && correctTime && !addedHistoryWithTime && checkNumChannel )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                    }
                }
                else if ( si11 )
                {
                    if( currentVersion >= 2 )
                    {
                        var checkNumChannel = validSelectedChannel && ( history.reason == selectedChannel.num_channel );
                        if ( all && correctTs && !addedHistoryWithTs )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                        else if ( !all && channelImpulse && correctTime && !addedHistoryWithTime && history.port == 2 )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                        else if ( !all && channelDanger && correctTime && !addedHistoryWithTime && (checkNumChannel || history.reason == 5) && history.port == 2 )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                    }
                    else
                    {
                        var checkNumChannel = validSelectedChannel && ( history.num_channel == selectedChannel.num_channel );
                        if ( all && correctTs && !addedHistoryWithTs )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                        else if ( !all && channelImpulse && history.type == 1 && correctTime && !addedHistoryWithTime )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                        else if ( !all && channelDanger && history.type == 2 && correctTime && !addedHistoryWithTime && checkNumChannel )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                    }
                }
                else if ( si12  )
                {
                    if( currentVersion >= 2 )
                    {
                        // if(all) console.log(history.reason);
                        var checkNumChannelDanger = validSelectedChannel && ( history.reason == selectedChannel.num_channel );
                        
                        if ( all && correctTs && !addedHistoryWithTs )
                        {
                            // if(history.fcnt == 260) 
                            // {
                            //     console.log('Фильтруем',history.reason);
                            // }
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                        else if ( !all && channelImpulse && correctTime && !addedHistoryWithTime && history.port == 2 )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                        else if ( !all && channelDanger && correctTime && !addedHistoryWithTime && ( checkNumChannelDanger ) && history.port == 2 )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                    }
                    else
                    {
                        var checkNumChannel = validSelectedChannel && ( history.num_channel == selectedChannel.num_channel );
                        if ( all && correctTs && !addedHistoryWithTs )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                        else if ( !all && channelImpulse && history.type == 1 && correctTime && !addedHistoryWithTime )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                        else if ( !all && channelDanger && history.type == 2 && correctTime && !addedHistoryWithTime && checkNumChannel )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                    }
                }
                else if( si13 )
                {
                    if ( all && correctTs && !addedHistoryWithTs )
                    {
                        tempObject[history.ts] = history.ts;
                        temp.push( history );
                    }
                    else
                    {
                        if( channelImpulse )
                        {
                            if ( version == 0 )
                            {
                                if ( correctTs && history.type == 1 && !addedHistoryWithTs )
                                {
                                    tempObject[history.ts] = history.ts;
                                    temp.push( history );
                                }
                            }
                            else if ( version == 1 )
                            {
                                if ( correctTime && history.type == 1 && !addedHistoryWithTime )
                                {
                                    tempObject[history.time] = history.time;
                                    temp.push( history );
                                }
                            }
                        }
                        else if ( channelSi13Merc || channelSi13ModBus )
                        {
                            if ( version == 0 )
                            {
                                if ( correctTs && correctTypePackage && !addedHistoryWithTs )
                                {
                                    tempObject[history.ts] = history.ts;
                                    temp.push( history );
                                }
                            }
                            else if ( version == 1 )
                            {
                                if ( all && correctTs && !addedHistoryWithTs )
                                {
                                    tempObject[history.ts] = history.ts;
                                    temp.push( history );
                                }
                                else if ( correctTime && correctTypePackage && !addedHistoryWithTime )
                                {
                                    tempObject[history.time] = history.time;
                                    temp.push( history );
                                }
                            }
                        }
                        else if( channelDanger )
                        {
                            var checkNumChannel = validSelectedChannel && ( (history.num_channel+6) == selectedChannel.num_channel );
                            if ( version == 0 )
                            {
                                if ( correctTs && history.type == 2 && !addedHistoryWithTs && checkNumChannel)
                                {
                                    tempObject[history.ts] = history.ts;
                                    temp.push( history );
                                }
                            }
                            else if ( version == 1 )
                            {
                                if ( correctTime && history.type == 2 && !addedHistoryWithTime && checkNumChannel )
                                {
                                    tempObject[history.time] = history.time;
                                    temp.push( history );
                                }
                            }
                        }
                    }
                }
                else if( sh02 )
                {
                    if ( all )
                    {
                        if(!correctTs || addedHistoryWithTs) continue;
                        tempObject[history.ts] = history.ts;
                        temp.push( history );
                    }
                    else
                    {
                        if( channelImpulse || channelAnalogue )
                        {
                            if ( correctTime && !addedHistoryWithTime )
                            {
                                tempObject[history.time] = history.time;
                                temp.push( history );
                            }
                        }
                        else if (currentVersion >= 1 && channelSi13ModBus && history.type2 == 13 ||
                            currentVersion >= 2 && channelSi13ModBus && (history.type == 4 || history.type == 6)
                        ) {
                            if ( correctTime && !addedHistoryWithTime )
                            {
                                tempObject[history.time] = history.time;
                                temp.push( history );
                            }
                        }
                        else if (currentVersion >= 1 && channel1Wire && history.type2 == 12 ||
                            currentVersion >= 2 && channel1Wire && history.type == 0x0B
                        ) {
                            if ( correctTime && !addedHistoryWithTime )
                            {
                                tempObject[history.time] = history.time;
                                temp.push( history );
                            }
                        }
                        else if ( ( currentVersion == 0 || !currentVersion) && channelSi13ModBus && history.type == 9 )
                        {
                            if ( correctTime && correctTypePackage && !addedHistoryWithTime )
                            {
                                tempObject[history.time] = history.time;
                                temp.push( history );
                            }
                        }
                        else if ( ( currentVersion == 0 || !currentVersion) && channel1Wire && history.type == 1 )
                        {
                            if ( correctTime && correctTypePackage && !addedHistoryWithTime )
                            {
                                tempObject[history.time] = history.time;
                                temp.push( history );
                            }
                        }
                        else if( channelDanger && validSelectedChannel )
                        {
                            var v1 = history.reason == 2 && selectedChannel.num_channel == 1;
                            var v2 = history.reason == 3 && selectedChannel.num_channel == 2;
                            if ( correctTime && !addedHistoryWithTime && (v1 || v2) )
                            {
                                tempObject[history.time] = history.time;
                                temp.push( history );
                            }
                        }
                    }
                }
                else if ( channelImpulse )
                {
                    if ( all && correctTs && !addedHistoryWithTs )
                    {
                        tempObject[history.ts] = history.ts;
                        temp.push( history );
                    }
                    else if ( version == 0 )
                    {
                        if ( correctTs && history.type == 1 && !addedHistoryWithTs )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                    }
                    else if ( version == 1 )
                    {
                        if ( correctTime && history.type == 1 && !addedHistoryWithTime )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                    }
                }
                else if ( channelUG )
                {
                    if ( correctTime && history.port == 2 && !addedHistoryWithTime )
                    {
                        tempObject[history.time] = history.time;
                        temp.push( history );
                    }
                }
                // else if ( channelSi13Merc || channelSi13ModBus )
                // {
                //     if ( all && correctTs && !addedHistoryWithTs )
                //     {
                //         tempObject[history.ts] = history.ts;
                //         temp.push( history );
                //     }
                //     else if ( version == 0 )
                //     {
                //         if ( all && correctTs && !addedHistoryWithTs )
                //         {
                //             tempObject[history.ts] = history.ts;
                //             temp.push( history );
                //         }
                //         else if ( correctTs && correctTypePackage && !addedHistoryWithTs )
                //         {
                //             tempObject[history.ts] = history.ts;
                //             temp.push( history );
                //         }
                //     }
                //     else if ( version == 1 )
                //     {
                //         if ( all && correctTs && !addedHistoryWithTs )
                //         {
                //             tempObject[history.ts] = history.ts;
                //             temp.push( history );
                //         }
                //         else if ( correctTime && correctTypePackage && !addedHistoryWithTime )
                //         {
                //             tempObject[history.time] = history.time;
                //             temp.push( history );
                //         }
                //     }
                // }
                else if ( channelUE && (ue||ue_merc) )
                {
                    if ( all && date_range.compareUTC( history.ts ) && !addedHistoryWithTs )
                    {
                        tempObject[history.ts] = history.ts;
                        temp.push( history );
                    }
                    else if ( date_range.compare_unixUTC( history.time ) && correctTypePackage && !addedHistoryWithTime )
                    {
                        tempObject[history.time] = history.time;
                        temp.push( history );
                    }
                }
                else if ( channelUE && ue_spbzip )
                {
                    if ( all && date_range.compareUTC( history.ts ) && !addedHistoryWithTs )
                    {
                        tempObject[history.ts] = history.ts;
                        temp.push( history );
                    }
                    else if ( ( history.type == 16 || history.type == 17 ) && correctTypeArchiveSPBZIP && date_range.compare_unixUTC( history.time ) )
                    {
                        tempObject[history.time] = history.time;
                        temp.push( history );
                    }
                    else if ( history.type == 18 && correctTypePackage && !addedHistoryWithTs && date_range.compareUTC( history.ts ) )
                    {
                        tempObject[history.ts] = history.ts;
                        temp.push( history );
                    }
                    else if ( correctJournalSPBZIP  && !addedHistoryWithTs && date_range.compareUTC( history.ts ) )
                    {
                        tempObject[history.ts] = history.ts;
                        temp.push( history );
                    }
                    else if ( date_range.compare_unixUTC( history.time ) && correctTypePackage && !addedHistoryWithTime )
                    {
                        tempObject[history.time] = history.time;
                        temp.push( history );
                    }
                    
                }
                else if ( channelDanger )
                {
                    var other = !si13 && !mbus1 && !mbus2 ;
                    // if( si13 )
                    // {

                    //     var checkNumChannel = validSelectedChannel && ( (history.num_channel+6) == selectedChannel.num_channel );
                    //     if ( all && correctTs && !addedHistoryWithTs )
                    //     {
                    //         tempObject[history.ts] = history.ts;
                    //         temp.push( history );
                    //     }
                    //     else if ( version == 0 )
                    //     {
                    //         if ( correctTs && history.type == 2 && !addedHistoryWithTs && checkNumChannel)
                    //         {
                    //             tempObject[history.ts] = history.ts;
                    //             temp.push( history );
                    //         }
                    //     }
                    //     else if ( version == 1 )
                    //     {
                    //         if ( correctTime && history.type == 2 && !addedHistoryWithTime && checkNumChannel )
                    //         {
                    //             tempObject[history.time] = history.time;
                    //             temp.push( history );
                    //         }
                    //     }
                    // }
                    if( mbus1 ||  mbus2)
                    {
                        var checkNumChannel = validSelectedChannel && ( (history.num_channel+10) == selectedChannel.num_channel );
                        if ( all && correctTs && !addedHistoryWithTs )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                        else if(  history.type == 5 && correctTs && !addedHistoryWithTs && checkNumChannel )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                        
                    }
                    else if ( other )
                    {
                        if ( correctTime && history.type == 2 && tempObject[history.time] == undefined )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                    }
                }
                else if ( channelTD11 && td11 )
                {
                    if ( version == 0 )
                    {
                        if ( correctTs && history.type == 1 && !addedHistoryWithTs )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                    }
                    else if ( version == 1 )
                    {
                        if ( correctTime && history.type == 1 && !addedHistoryWithTime )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                    }
                }
                else if ( channelTP11 )
                {
                    if ( version == 0 )
                    {
                        if ( correctTs && !addedHistoryWithTs )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                    }
                    else if ( version == 1 )
                    {
                        if ( correctTime && !addedHistoryWithTime )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                    }
                }
                else if ( ss2 )
                {
                    if ( all && correctTs && !addedHistoryWithTs )
                    {
                        tempObject[history.ts] = history.ts;
                        temp.push( history );
                    }
                    else if ( correctTime && !addedHistoryWithTime && history.port == 2 )
                    {
                        tempObject[history.time] = history.time;
                        temp.push( history );
                    }
                }
                else if ( channelSMART )
                {
                    if ( version == 0 || ss )
                    {
                        if ( correctTs && history.type == 1 && !addedHistoryWithTs )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                    }
                    else if ( version >= 1 && !ss )
                    {
                        if ( all && correctTs && !addedHistoryWithTs )
                        {
                            tempObject[history.ts] = history.ts;
                            temp.push( history );
                        }
                        else if ( correctTime && !addedHistoryWithTime )
                        {
                            tempObject[history.time] = history.time;
                            temp.push( history );
                        }
                    }
                }
                else if ( channelLM11 )
                {
                    if (correctTime && history.type==1 && !addedHistoryWithTime)
                    {
                        tempObject[history.time] = history.time;
                        temp.push( history );
                    }
                }
                else if ( channelSRC )
                {
                    if (correctTime && !addedHistoryWithTime)
                    {
                        tempObject[history.time] = history.time;
                        temp.push( history );
                    }
                }
                else if ( channelTL11 )
                {
                    if ( correctTime && history.port == 2 && !addedHistoryWithTime )
                    {
                        tempObject[history.time] = history.time;
                        temp.push( history );
                    }
                }
                else if ( channelSVE )
                {
                    var duplicate = tmp_o[history.time] != undefined;
                    if ( sve && !duplicate )
                    {
                        if ( correctTime && history.type == 1 )
                        {
                            tmp_o[history.time] = true;
                            temp.push( history );
                        }
                    }
                }
                else if ( channelMBUS )
                {
                    var validAddress = currentAddress == selectedChannel.ia;
                    var duplicate = tempObject[history.time] != undefined;
                    if ( type_package=='all' && date_range.compareUTC( history.ts ) && !addedHistoryWithTs )
                    {
                        tempObject[history.ts] = history.ts;
                        temp.push( history );
                    }
                    else if ( correctTime && history.type == 1 && validAddress  && !addedHistoryWithTs && !addedHistoryWithTime )
                    {
                        tempObject[history.time] = true;
                        temp.push( history );
                    }
                }
                else if ( channelTherm )
                {
                    var validAddressH = typeof history.address === 'string';
                    var validAddressC = typeof selectedChannel.mac === 'string';
                    var validAddress = validAddressH && validAddressC && history.address.toLowerCase() == selectedChannel.mac.toLowerCase();
                    var duplicate = tempObject[history.time] != undefined;
                    if ( type_package=='all' && date_range.compareUTC( history.ts ) && !addedHistoryWithTs )
                    {
                        tempObject[history.ts] = history.ts;
                        temp.push( history );
                    }
                    else if ( correctTime && history.type == 1 && validAddress  && !addedHistoryWithTs && !addedHistoryWithTime )
                    {
                        tempObject[history.time] = true;
                        temp.push( history );
                    }
                }
                else if ( channelHS || channelUM )
                {
                    var duplicate = tmp_o[history.time] != undefined;
                    if ( !duplicate )
                    {
                        if ( correctTime )
                        {
                            tmp_o[history.time] = true;
                            temp.push( history );
                        }
                    }
                }
            }
            // console.log('------------');
            // for (var j = 0; j<temp.length;j++){
            //     if(temp[j].fcnt == 260) 
            //     {
            //         console.log('Когда возвращаеться значение фильтра',temp[j].reason);
            //     }
            // }
            // console.log('------------');
            return temp;
        }
        catch (err)
        {
            return new Array();
        }
    }
})
      .filter('filter_type_channel',function (){
    return function(items,data)
    {
        var temp = new Array();
        for (var i=0; i<items.length;i++)
        {
            if (items[i].type==1&&temp.indexOf(items[i])==-1)
            {
                temp.push(items[i]);
            }
        }
            return temp;
        }
       

    
})  
.filter('filter_list',function (){
    return function(items,data)
    {
        return items;
    }   
}) 
;
angular.module('naturalSort', new Array())
// The core natural service
.factory('naturalService', function () {
	'use strict';
		// amount of extra zeros to padd for sorting
    var padding = function(value) {
			return '00000000000000000000'.slice(value.length);
		},

		// Converts a value to a string.  Null and undefined are converted to ''
		toString = function(value) {
			if (value === null || value === undefined) {return '';}
			return ''+value;
		},

		// Fix numbers to be correctly padded
        natValue = function(value,param_str) {
			// First, look for anything in the form of d.d or d.d.d...
            if (param_str!==undefined&& isObject(value) ) value = value[param_str];
            return toString(value).replace(/(\d+)((\.\d+)+)?/g, function ($0, integer, decimal, $3) {
				// If there's more than 2 sets of numbers...
                if (decimal !== $3) {
                    // treat as a series of integers, like versioning,
                    // rather than a decimal
                    return $0.replace(/(\d+)/g, function ($d) {
                        return padding($d) + $d;
                    });
                } else {
					// add a decimal if necessary to ensure decimal sorting
                    decimal = decimal || '.0';
                    return padding(integer) + integer + decimal + padding(decimal);
                }
            });
        };

	// The actual object used by this service
	return {
		naturalValue: natValue,
		naturalSort: function(a, b) {
			a = natValue(a);
			b = natValue(b);
			return (a < b) ? -1 : ((a > b) ? 1 : 0);
		}
	};
})

// Attach a function to the rootScope so it can be accessed by 'orderBy'
.run(['$rootScope', 'naturalService', function($rootScope, naturalService) {
	'use strict';
	$rootScope.natural = function (param_str) {
        return function (item) {
            return naturalService.naturalValue(item,param_str);
        };
    };
}])
// .directive('maToSensor', function() {
//     var convert = new vega_converter();
//     return {
//       require: 'ngModel',
//       link: function(scope, element, attrs, ngModel) {
//         var min = parseFloat(attrs.minV);
//         var max = parseFloat(attrs.maxV);
//         ngModel.$parsers.push(function(value) {
//             var limit = parseFloat(value);
//             var ma = convert.to4_20mA(limit,min,max) * 100 ;
//             var result = Math.round(ma);
//             return  result;
//         });
//         ngModel.$formatters.push(function(value) {
//             var val = convert.parse4_20mA(parseFloat(value/100),min,max);
//             var result = Math.round(val*100)/100;
//             return result;
//         });
//       }
//     };
// });
$('#sendDataDevice').on('shown.bs.modal', function (e) {
   var scope = angular.element('body').scope();
});
$('#sendDataDevice').on('hide.bs.modal', function (e) {
   var scope = angular.element('body').scope();
    var channel = scope.storage.devices.select_channel_temp;
    channel.edit_out = undefined;
})

window.onbeforeunload = function(evt){
    if (!get_cookie('command_list'))
    {
        return null;
    }
    return "Вы действительно хотите покинуть эту страницу?";
}
window.onpopstate = function(event) {
    if (event.state)
    {
        var scope = angular.element('body').scope();
        if (event.state.page==2)
        {
            if (scope.storage.devices.select_channel_temp.name!==undefined)
            {
                scope.check_page = event.state.page;
                scope.type_active_page = 0;
            }
            else
            {
                
            }
        }
        else
        {
            scope.check_page = event.state.page;
            scope.type_active_page = 0;
        }
        scope.$apply(function (){ 
            scope.type_active_page; 
            scope.check_page; 
        }) 
    }
    else
    {
        scope.universalConfirm('Внимание!',
        "Вы действительно хотите покинуть эту страницу?",
        ()=>{
            history.back()
        }
        );
        // if (confirm("Вы действительно хотите покинуть эту страницу?"))
        // {
        //     history.back()
        // }
        // else
        // {
            
        // }
    }
};